【问题标题】:How do you refer to separate instances of elements of a re-used layout in Android?您如何引用 Android 中重用布局的元素的单独实例?
【发布时间】:2014-06-29 21:54:49
【问题描述】:

我创建了一个包含三个数字选择器的片段布局。 我曾经在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,但我当前的实现似乎更清晰。

非常感谢!

【问题讨论】:

    标签: java android xml layout numberpicker


    【解决方案1】:

    您可以像这样以编程方式引用您的视图:

    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 部分。

    【讨论】:

    • 我知道我可以使用 findViewById 来获取我的数字选择器,我只是不确定返回的是哪一个,因为定义每个选择器的布局被使用了两次。将 findViewId(R.id.redPicker) 分配给 redPicker,然后对 redPicker 执行某些操作(例如 setMinValue)将更改首先显示的 redPicker,但不会更改第二个,我想知道如何更改它们。
    【解决方案2】:

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

    How to specify id when uses include in layout xml file

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      • 2020-08-21
      相关资源
      最近更新 更多