1

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" />

私の主な活動

TextView gpsStatus = (TextView)findViewById(R.id.gpsStatus); // gpsStatus = null
gpsStatus.setText("foo");

これにより、nullpointerexceptionが発生します。

LayoutInflater inflater = getLayoutInflater();
View homeView = inflater.inflate(R.layout.home, null);
TextView gpsStatus = (TextView)homeView.findViewById(R.id.gpsStatus);
gpsStatus.setText("foo");

これでコードがクラッシュすることはありませんが、テキストも変更されません。

では、自分の中にあるコントロールを見つけて操作するにはどうすればよいmain.xmlですか?

ありがとう

4

2 に答える 2

1

これは、findViewById を呼び出すときに、メイン アクティビティに home.xml が存在しないためです。home.xml レイアウト ファイルがメイン アクティビティにインフレートされると、findViewById が機能するはずです。

findViewById は、現在のビュー階層の下にある ID に対してのみ機能します。膨張したビューで findViewById を呼び出すことにより、特に作成したレイアウト オブジェクトでビュー階層をチェックしています。

メイン アクティビティ内のビューに home.xml レイアウトを追加すると、アクティビティのビュー階層に追加され、findViewById と setText の呼び出しが機能します。

于 2012-07-07T17:23:18.443 に答える
1

So how do i find and manipulate controls that arent located in my main.xml?

main.xmlでも

<LinearLayout 
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/aLyoutWillbeAddedIfruqired"
 >
</LinearLayout>

あなたの活動では、次のようなことをします...

LinearLayout statusLayout= (LinearLayout )findViewById(R.id.aLyoutWillbeAddedIfruqired);

LayoutInflater inflater = getLayoutInflater();
View homeView = inflater.inflate(R.layout.home, null);
TextView gpsStatus = (TextView)homeView.findViewById(R.id.gpsStatus);
gpsStatus.setText("foo");
statusLayout.addView(homeView);

お役に立てば幸いです...

于 2012-07-07T17:33:15.480 に答える