Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how to make findViewById(R.id.xxx) working in a class inheriting/extending from the View class?

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

like image 596
Regis_AG Avatar asked Oct 11 '11 10:10

Regis_AG


People also ask

What is findViewById () method used for?

FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.

What is r in findViewById?

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

What is the return type of findViewById INT Viewid method?

Returns. The view if found or null otherwise.


1 Answers

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);
like image 71
PH7 Avatar answered Nov 15 '22 03:11

PH7