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
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.