Reputation: 4201
In my application I call setContentView( layout1.xml );
, I want to access an element within a DIFFERENT layout file, lets call it layout2.xml.
I have tried
view1 = (View) findViewById( R.layout.layout2 );
and also added an id to the layout and tried
view1 = (View) findViewById( r.id.layout2 );
Neither of these work. They compile just fine but when I run it, as soon as i try to call something like
button1 = view1.findViewById( R.id.button1 );
I get a null pointer exception.
Upvotes: 0
Views: 93
Reputation: 977
You can access an element from layout2 by inflating it first as follows:
LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.layout2, null);
//or View view = (View)inflater.inflate(R.layout.layout2, null);
Button button = (Button)layout.findViewById(R.id.button1);
//add code for button
Upvotes: 2
Reputation: 3294
You need to use a layout inflater to get your second layout like so:
View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.layout2, null);
And then reference your button from that layout:
Button button1 = view.findViewById( R.id.button1 );
Upvotes: 2