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