Android Java: How to get component in a custom view? (Trying to access components via findByViewId and get null)

271 views Asked by At

Trying to access components via findByViewId and get null The problem is in this line:

(I cannot connect my viewxml to the class)

// HERE I GET NULL
    **_addButton     = context.findViewById(R.id.buttonAdd);**

I have an activity: with this OnCreate:

MainActivity class

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
}

I have a custom view I call in my MainActivity MainActivity xml

   <com.example.myemptyapplication.PlayersFragment
        android:id="@+id/fragment_container_view_players"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="10px"/>

In 'PlayersFragment' I' trying to access

PlayersFragment extends View
@RequiresApi(api = Build.VERSION_CODES.O)
    public PlayersFragment(Context context, AttributeSet attSet) {
        super(context, attSet);
 protected void onFinishInflate() {
        super.onFinishInflate();
    // HERE I GET NULL
        **_addButton     = context.findViewById(R.id.buttonAdd);**
    }

Tried to get components in a custom view

2

There are 2 answers

2
Gabe Sechan On BEST ANSWER

1)Don't call views Fragments. Fragments are a separate concept in Android, and your code will confuse everyone.

2)If you created that view as a subview of your custom view, you'd use findViewById, not context.findViewById. Because the view isn't in the context, its one of your subviews.

0
Tammy Roytvarf On

Thanks to all!!! I've found a way to connect the xml to the View class:

ayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.fragment_players, null, false);