繁体   English   中英

您如何在Android中引用重复使用的布局元素的单独实例?

[英]How do you refer to separate instances of elements of a re-used layout in Android?

我创建了一个包含三个数字选择器的片段布局。 我曾经在activity_main.xml中两次使用此片段。 两组数字选择器均正确显示,但是我不确定如何以编程方式操作它们,因为我不知道如何分别引用每个数字选择器。 基本上,我想知道给定我当前的布局实现是否可以分别引用每个数字选择器。

picker_fragment.xml代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/picker_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="horizontal" >

<NumberPicker
    android:id="@+id/redPicker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
 />
<NumberPicker
    android:id="@+id/greenPicker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
<NumberPicker
    android:id="@+id/bluePicker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

activity_main.xml代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.colorpickertwo.MainActivity"
tools:ignore="MergeRootFrame" >

<include layout="@layout/picker_fragment"/>
<include layout="@layout/picker_fragment"/>


</LinearLayout>

我可以放弃我的picker_fragment,或者进行第二个片段布局,以便提供第二组数字选择器的独立ID,但是我当前的实现似乎更简洁。

非常感谢!

通过编程,您可以像下面这样引用您的视图:

NumberPicker redPicker = (NumberPicker)findViewById(R.id.redPicker);
NumberPicker greenPicker = (NumberPicker)findViewById(R.id.redPicker);
NumberPicker bluePicker = (NumberPicker)findViewById(R.id.bluePicker);

// and then do something with redPicker...

这是来自android的View文档,请检查ID部分。

我在这里找到答案! 这个人也比我更好地表达了我的问题。

在布局XML文件中使用包含时如何指定ID

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM