use*_*146 2 java layout android 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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
由于根元素是a LinearLayout,它扩展了ViewGroup,为什么main.xml变成a 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());
Run Code Online (Sandbox Code Playgroud)
但是当我打电话时它崩溃了vg.getChildCount().
这样做的正确方法是什么?
findViewById应该采取定义的视图的ID 内的布局的XML文件,而不是文件本身的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>
Run Code Online (Sandbox Code Playgroud)
通过:
ViewGroup vg = (ViewGroup) findViewById(R.id.mainlayout);
Run Code Online (Sandbox Code Playgroud)
请注意添加android:id属性以及R.id在findViewById调用中使用匹配值.它与开发指南中描述的用法相同.然后,您应该能够安全地将结果转换为ViewGroup或LinearLayout.
如果您希望单独加载主视图,例如作为子视图,请使用getLayoutInflater().inflate(...)构建和检索它.
| 归档时间: |
|
| 查看次数: |
2717 次 |
| 最近记录: |