use*_*759 32 layout android include
我已经在Android开发人员上阅读了Android UI技巧2,它告诉人们如何多次在另一个布局文件中包含布局,并为这些布局提供不同的ID.但是,此处的示例是覆盖布局ID,而不是此布局中视图的ID.例如,如果workspace_screen.xml如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="@+id/firstText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="first"/>
<TextView android:id="@+id/secondText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="second"/>
Run Code Online (Sandbox Code Playgroud)
我在另一个布局文件中包含了三次.我最终得到三个带有id firstText的TextView,还有另外三个带有secondText的TextView?是不是有碰撞?如何在findViewById的第三个包含布局中找到secondText TextView?我应该在findViewById方法中输入什么?
小智 68
假设您要包含此内容:
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
>
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/some_image"
/>
<TextView
android:id="@+id/included_text_view"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
所以在你的代码中你插入它像这样:
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="vertical"
>
<include android:id="@+id/header_1" layout="@layout/name_of_layout_xml" />
<include android:id="@+id/header_2" layout="@layout/name_of_layout_xml" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
现在,您希望访问包含的布局中的文本视图以动态设置文本.在您的代码中,您只需输入:
LinearLayout ll = (LinearLayout)findViewById(R.id.header_1);
TextView tv = (TextView)ll.findViewById(R.id.included_text_view);
tv.setText("Header Text 1");
ll = (LinearLayout)findViewById(R.id.header_2);
tv = (TextView)ll.findViewById(R.id.included_text_view);
tv.setText("Header Text 2");
Run Code Online (Sandbox Code Playgroud)
请注意,您使用各个LinearLayouts的findViewById方法将搜索范围缩小到仅限于其子项.
| 归档时间: |
|
| 查看次数: |
12907 次 |
| 最近记录: |