I have the following problem: I want to add a custom view (custom_view.xml and associated CustomView.java class) to my main activity.
So, I do the following:
1) In my main activity (linked to main.xml):
CustomView customView = new CustomView(this);
mainView.addView(customView);
2) In my CustomView.java class (that I want to link to custom_view.xml):
public class CustomView extends View {
public CustomView(Context context)
{
super(context);
/* setContentView(R.layout.custom_view); This doesn't work here as I am in a class extending from and not from Activity */
TextView aTextView = (TextView) findViewById(R.id.aTextView); // returns null
///etc....
}
}
My problem is that aTextView remains equal to null... It seems clearly due to the fact that my custom_view.xml is not linked to my CustomView.java class. How can I do this link ? Indeed, I tried setContentView(R.layout.custom_view); but it doesn't work (compilation error) as my class extends from View class and not Activity class.
Thanks for your help !!
FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.
R is a Class that contains the ID's of all the Views. findViewById is the method that finds the View by the ID it is given. So findViewById(R. id. myName) finds the View with name 'myName'.
Returns. The view if found or null otherwise.
If I get you correctly, you are trying to build customview from layoutfile(R.layout.custom_view). You want to find a textview from that layout file. Is that right?
If so, you need to inflate the layout file with context u have. Then u can find the textview from the layout file.
Try this.
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.custom_view, null);
TextView aTextView = (TextView) v.findViewById(R.id.aTextView);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With