Java /res/layout/main.xml是否描述视图或视图组?
我的Java /res/layout/main.xml是否描述视图或视图组?,java,android,layout,view,Java,Android,Layout,View,我的main.xml如下所示: <?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"
main.xml
如下所示:
<?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>
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()
时,它崩溃了
正确的方法是什么?应该采用布局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>
注意添加了一个android:id
属性,并在findViewById
调用中使用了匹配的R.id
值。它的用法与中描述的相同。然后,您应该能够将结果安全地强制转换为视图组
或线性布局
如果您希望单独加载主视图(例如作为子视图),请使用。构建并检索它。您是否查看了日志猫中的异常?Android开发人员已经做了相当好的工作,让你知道他们给出的异常出了什么问题。。谢谢
ViewGroup vg = (ViewGroup) findViewById(R.id.mainlayout);