main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp"
android:background="@drawable/gradientbg" >
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/viewPager"/>
</LinearLayout>
home.xml
<TextView
android:id="@+id/gpsStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="2dp" />
my main activity
TextView gpsStatus = (TextView)findViewById(R.id.gpsStatus); // gpsStatus = null
gpsStatus.setText("foo");
This will result in a nullpointerexception.
LayoutInflater inflater = getLayoutInflater();
View homeView = inflater.inflate(R.layout.home, null);
TextView gpsStatus = (TextView)homeView.findViewById(R.id.gpsStatus);
gpsStatus.setText("foo");
This wont crash the code, but it wont change my text either.
So how do i find and manipulate controls that arent located in my main.xml?
Thanks
This is because your home.xml does not exist in your main activity when you are calling findViewById. Once your home.xml layout file is inflated into your main activity, findViewById should work.
findViewById only works for IDs that are under the current view hierarchy. By calling findViewById on your inflated view, you are checking the view hierarchy specifically on the layout object you created.
If you add your home.xml layout to a view inside your main activity, it will be added to your activity’s view hierarchy, and then your findViewById and setText calls will work.