2012-07-07 31 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