2012-07-07 30 views
0

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中的控件?

感謝

+0

@ user370305'.ClassCastException:android.widget.LinearLayout不能轉換爲android.widget.TextView' – Johan 2012-07-07 17:04:23

+0

你的Home.xml文件包含更多視圖還是隻包含TextView? – user370305 2012-07-07 17:05:26

+0

@ user370305其中包含textview的線性佈局。 – Johan 2012-07-07 17:06:48

回答

1

這是因爲當你調用findViewById您home.xml不會在您的主要活動存在。一旦你的home.xml佈局文件被充滿你的主要活動,findViewById應該可以工作。

findViewById僅適用於當前視圖層次結構下的ID。通過在您的虛擬視圖上調用findViewById,您正在特定於您創建的佈局對象上檢查視圖層次結構。

如果您將home.xml佈局添加到主活動中的視圖中,它將被添加到活動的視圖層次結構中,然後您的findViewById和setText調用將會起作用。

+0

好吧,我將如何將它添加到我的主要活動內的視圖? – Johan 2012-07-07 17:26:35

+0

有很多不同的方法。您可以直接將home.xml包含到main.xml佈局中(請參閱http://developer.android.com/training/improving-layouts/reusing-layouts.html或http://stackoverflow.com/questions/8834898/use -of-Android的XML合併標籤)。或者,您可以使用佈局充氣器充氣您的視圖,然後將其添加到視圖組。 – WindyB 2012-07-07 17:30:33

+0

或者,您也可以使用PagerAdapter將視圖加載到ViewPager中。有關詳細信息,請參閱http://developer.android.com/reference/android/support/v4/view/PagerAdapter.html。 – WindyB 2012-07-07 17:31:20

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); 

我希望它會HEL p你...

+0

是的,這是我需要的,+1和謝謝 – Johan 2012-07-07 17:35:13