5

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

toto_tata
  • 14,526
  • 27
  • 108
  • 198
  • shouldn't you be inflating your xml at some point? – njzk2 Oct 11 '11 at 10:26
  • Thanks njzk2. It seems that I should inflate my xml. How can I do that ? (thanks for your answer in case I don't find any blog on this topic) – toto_tata Oct 11 '11 at 10:31

3 Answers3

12

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);
PH7
  • 3,926
  • 3
  • 24
  • 29
1

I would suggest you to try this:

TextView aTextView = (TextView) ((Activity)this.getContext()).findViewById(R.id.aTextView);

It worked for me!!!

Pontios
  • 2,377
  • 27
  • 32
0

Try inflating the customView.

Second, try (I presume that aTextView id is present in side CustomView)

TextView aTextView = (TextView) mainView.findViewById(R.id.aTextView);
Vinay
  • 2,395
  • 3
  • 30
  • 35