Solution 1 :
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.
Solution 2 :
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);
Problem :
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
Comments
Comment posted by CommonsWare
There is no sign of anything named
Comment posted by Bracadabra
What is context in your snippet? If it is Android context, then there is no findViewById method.
Comment posted by Tammy Roytvarf
buttonAdd this commin from an XML:
Comment posted by Tammy Roytvarf
Thanks! (2) this actually what what actually worked.
Comment posted by Gabe Sechan
@TammyRoytvarf 1 wasn’t a way to solve it , it was advice. Calling them Fragments when Fragments are a separate major concept in Android confuses everyone who reads the code.