2010-07-27 59 views
2

main.xml看起来像这样:/res/layout/main.xml是否描述View或ViewGroup?

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
> 
<TextView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello" 
/> 
</LinearLayout> 

由于根元素是LinearLayout,延伸ViewGroup,为什么main.xml得到变成了View而不是ViewGroup?举例来说,在我的主要Activity类,我试图让子视图数量的LinearLayout包含这样的:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    ViewGroup vg = (ViewGroup) findViewById(R.layout.main); 
    Log.v("myTag", "num children: " + vg.getChildCount()); 

但是当我打电话vg.getChildCount()它崩溃。

这样做的正确方法是什么?

+0

你看看LogCat的异常吗? Android开发者已经做了很好的工作,让你知道他们发布的Exceptions出了什么问题。 – 2010-07-27 03:25:45

回答

6

findViewById应该采取定义内部的布局的XML文件,而不是文件本身的ID的视图的ID。一旦你已经膨胀的观点,无论是手动或通过setContentView,你可以得到的布局与它,如果你已经这样做了:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:id="@+id/mainlayout" 
> 
<TextView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello" 
/> 
</LinearLayout> 

通过:

ViewGroup vg = (ViewGroup) findViewById(R.id.mainlayout); 

注加的android:id属性和findViewById调用中匹配的R.id值的使用。这与Dev Guide中所述的用法相同。然后您应该能够安全地将结果转换为ViewGroupLinearLayout

如果您想单独加载主视图,例如,作为子视图,使用getLayoutInflater()inflate(...)来构建和检索它。

+0

作品超好..谢谢 – 2015-06-06 07:09:49