Reputation: 1875
We have MainActivity.class , activity_main.xml and firstlayout.xml.
In firstlayout.xml there is a listview
. I am in MainActivity.class and I want to access my listview.
How can I do that when my listview
is in another .xml file.
Something like
ListView lstview = (ListView) findViewById(R.id.lstview)
does not work, because I get a
null reference error
because my listview is not in mainactivity.xml. I also tried
setcontentView(R.layout.firstlayout)
but it didn't work either.
How can I access a xml file which is NOT in main_activity.xml ?
Upvotes: 1
Views: 1848
Reputation: 547
There are 2 possible way for useing ListView in your mainActivity.
1) You can simply include that layout (firstlayout.xml) into you activity_main.xml file.
example:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/app_bg"
android:gravity="center_horizontal">
<include layout="@layout/firstlayout"/>
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:padding="10dp" />
2) The second option is Layout Inflater.You can simply add other layout file directly into your java file.
LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(R.layout.firstlayout, this);
Upvotes: 2
Reputation: 2927
You can inflate your own:
View firstLayout = getLayoutInflater().inflate(R.layout.firstlayout, null, false);
ListView listView = (ListView) firstLayout.findViewById(R.id.lstView);
Just ensure that firstlayout
has a ListView
with id lstview
.
Upvotes: 1
Reputation: 1112
You can inflate the view with the layout inflater:
getLayoutInflater().inflate(R.layout.firstlayout,
parentView, //the view that logically contains the list view, or just the base view in the main layout
false // false if you want to attach the list view to the parent, true otherwise
);
Upvotes: 1