对 android 中的 onItemSelected 参数感到困惑

Confused about onItemSelected parameters in android

我在理解 Android 中的某些概念时遇到问题。我不太明白 parentview 在创建带有侦听器的微调器时必须定义的 onItemSelected 方法中特别提到(例如)。我查看了文档并尝试了几个示例,但这还不够。

我的主要问题来自我试验过的以下情况:我有一个微调器、一个包含项目 A、B 和 C 的数组,以及一个 link 它们的数组适配器。在 onItemSelected 方法中,我记录了父项的 ID 和视图以查看会发生什么。

无论我 select 来自列表(A、B 或 C)的哪一项,输出都是相同的:父项的 ID 为 W,视图的 ID 为 X。我希望父项保持不变,但我还希望视图 ID 在对应于我的 3 个项目的 3 个不同 ID(我们称它们为 X、Y 和 Z)之间发生变化。据我了解,在这样的列表中,每个项目都有自己的视图(因此有 ID)。

感谢您提供的任何说明。

我 运行 自己编写了一些代码并验证了我也遇到过这种情况。

您应该已经知道 onItemSelectedListener 界面属于 AdapterView class。在此 class 的 javadoc 中,您会发现这些有用的信息:

    /**
     * <p>Callback method to be invoked when an item in this view has been
     * selected. This callback is invoked only when the newly selected
     * position is different from the previously selected position or if
     * there was no selected item.</p>
     *
     * Implementers can call getItemAtPosition(position) if they need to access the
     * data associated with the selected item.
     *
     * @param parent The AdapterView where the selection happened
     * @param view The view within the AdapterView that was clicked
     * @param position The position of the view in the adapter
     * @param id The row id of the item that is selected
     */
    void onItemSelected(AdapterView<?> parent, View view, int position, long id);

您的第一个期望正确的onItemSelectedparent 参数引用与该微调器关联的 AdapterView。因此,只有一位父级具有特定 ID。

您的第二个期望错误的,尽管乍一看似乎合乎逻辑。让我们更深入地了解引擎盖下的实现。

当您在 Activity 或 Fragment 中的某个时刻使用 Spinner 时,您将执行以下操作:

Spinner spinner = (Spinner) findViewById(R.id.spinner);

// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
    R.array.planets_array, android.R.layout.simple_spinner_item);

// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// Apply the adapter to the spinner
spinner.setAdapter(adapter);

解释:

如文档中所述,createFromResource() 方法允许您从字符串数组创建 ArrayAdapter。此方法的第三个参数是布局资源,它定义所选选项在微调器控件中的显示方式。 simple_spinner_item 布局 由平台提供,是您应该使用的默认布局,除非您想为微调器的外观定义自己的布局。

然后您应该调用 setDropDownViewResource(int) 来指定适配器应该用来显示微调器选择列表的布局(simple_spinner_dropdown_item 是另一个由定义的标准布局平台)。

如果你打开这两个 xml 文件,simple_spinner_item 文件有一个普通的 TextViewsimple_spinner_dropdown_item 有一个普通的 CheckedTextView。您还会注意到它们都有一个 id 定义为:

android:id="@android:id/text1"

结论:

所以,很明显,由于您所有的微调项都使用相同的 xml 布局文件,因此它们使用具有相同属性和相同 ID 的相同 CheckedTextView。