问题描述
我在理解 Android 中的一些概念时遇到问题。我不太明白 parent 和 view 在 onItemSelected 方法中具体指的是什么在创建带有侦听器的微调器时定义(例如)。我查看了文档并尝试了一些示例,但还不够。
我的主要问题来自我试验过的以下情况:我有一个微调器、一个包含 A、B 和 C 项的数组,以及一个用于链接它们的数组适配器。在 onItemSelected 方法中,我记录了父级和视图的 ID 以查看会发生什么。
无论我从列表(A、B 或 C)中选择哪些项目,输出都是相同的:父级的 ID 为 W,视图的 ID 为 X。我希望父级保持不变,但是我还期望视图 ID 在与我的 3 个项目相对应的 3 个不同 ID(让我们称它们为 X、Y 和 Z)之间更改。我的理解是,在这样的列表中,每个项目都有自己的视图(以及 ID)。
感谢您提供的任何说明。
解决方法
我自己运行了一些代码并验证我也遇到过这种情况。
您应该已经知道 onItemSelectedListener 接口属于 AdapterView 类。在此类的 javadocs 中,您会发现这些有用的信息:
/**
* <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);
您的第一期望正确。 onItemSelected 的 parent 参数指的是与该微调器关联的 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 文件有一个普通的 TextView,simple_spinner_dropdown_item 有一个普通的 CheckedTextView强>。您还会注意到它们都有一个 id 定义为:
android:id="@android:id/text1"
结论:
因此,很明显,由于您的所有微调项都使用相同的 xml 布局文件,因此它们使用相同的 CheckedTextView,具有相同的属性,因此具有相同的 id。