main.xml中在不同的XML查找的TextView
<?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" />
我的主要活動
TextView gpsStatus = (TextView)findViewById(R.id.gpsStatus); // gpsStatus = null
gpsStatus.setText("foo");
這將導致nullpointere xception。
LayoutInflater inflater = getLayoutInflater();
View homeView = inflater.inflate(R.layout.home, null);
TextView gpsStatus = (TextView)homeView.findViewById(R.id.gpsStatus);
gpsStatus.setText("foo");
這不會崩潰的代碼,但它不會改變我的文字。
那麼,如何找到並操縱未在我的main.xml
中的控件?
感謝
@ user370305'.ClassCastException:android.widget.LinearLayout不能轉換爲android.widget.TextView' – Johan 2012-07-07 17:04:23
你的Home.xml文件包含更多視圖還是隻包含TextView? – user370305 2012-07-07 17:05:26
@ user370305其中包含textview的線性佈局。 – Johan 2012-07-07 17:06:48