<array-list> 根据用户选择显示 xml 中的项目



假设我有微调器,我从中选择存储在字符串数组中的项目,用户可以从中进行选择:

<string-array name="products_array">
<item>Sugar</item>
<item>Caster sugar</item>
<item>Salt</item>
</string-array>

我还有另外两个字符串数组列表,还有另一个值:

<string-array name="glass">
<item>200</item>
<item>180</item>
<item>325</item>
</string-array>

<string-array name="tableSpoon">
<item>25</item>
<item>25</item>
<item>30</item>
</string-array>

我已经创建了微调器,这是我的onItemSelected方法,如您所见,它显示了用户从列表中选择products_array的哪个项目(通过使用log.i):

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected = parent.getItemAtPosition(position).toString();
Log.i("Spinner listener", "Item selected " + selected);
}

我有一个布局文件(片段),其中我有微调器和两个文本视图 - 一个用于玻璃数组列表,一个用于 tableSpoon 数组列表。

我希望用户选择,比如说,Sugar,并在我的第一个TextView中相应地显示200的字符串数组玻璃,在我的第二个TextView中显示tableSpoon字符串数组25。

我希望这些值以确切的顺序显示,因为它们都在列表中(例如,Sugar 与 200 和 25 一起使用。脚轮糖与180和25等)

毫无疑问,可以使用 if-else 语句,但鉴于我在所有这些列表中将有相当多的值,我怎样才能更有效地做到这一点?

在 onItemSelected 方法中获取为产品数组选择的元素的位置,并将其保存在如下所示
的变量中

int index  = spinner1.getSelectedItemPosition(); // spinner1 is product spinner

然后从其他两个数组中获取此位置的值,并在您的文本视图中设置,
如下所示

String [] array1 = getResources().getStringArray(R.array.glass);
String [] array2 = getResources().getStringArray(R.array.tablespoon);

,然后在文本视图中设置值

textview1.setText(array1[index]);
textview2.setText(array2[index]);

1.从 XML 读取字符串数组glasstableSpoon,并将其存储到两个变量中,如下所示:

String [] glass = getResources().getStringArray(R.array.glass);
String [] tablespoon = getResources().getStringArray(R.array.tablespoon);

2.在方法onItemSelected()中,position获取所选项目,然后使用此position从数组glasstableSpoon中获取value

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
..........
..............
// Set text
firstTextView.setText(glass[position]);
secondTextView.setText(tableSpoon[position]);
}

希望这会有所帮助~

最新更新