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

时间:2014-06-29 21:54:49

标签: java android xml layout numberpicker

我创建了一个包含三个数字选择器的片段布局。 我曾经在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,或者制作第二个片段布局,以便给出第二组numberpicker的单独ID,但我当前的实现看起来更清晰。

非常感谢!

2 个答案:

答案 0 :(得分:0)

以编程方式,您可以像这样参考您的观点:

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...

Here's从android查看文档,检查ID部分。

答案 1 :(得分:0)

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

How to specify id when uses include in layout xml file