【问题标题】:Displaying item from xml <array-list> according to user selection根据用户选择显示来自 xml <array-list> 的项目
【发布时间】:2017-10-12 03:14:49
【问题描述】:

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

<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);
}

我有一个布局文件(片段),其中有微调器和两个 textView——一个用于 glass 数组列表,一个用于 tableSpoon 数组列表。

我希望用户选择,比如说,Sugar,并让它从 string-array glass 在我的第一个 TextView 中相应地显示 200,并且对于 tableSpoon 字符串数组 在我的第二个 TextView 中为 25。

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

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

【问题讨论】:

    标签: java android arrays xml


    【解决方案1】:

    在您的 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]);
    

    【讨论】:

      【解决方案2】:

      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]);
      }
      

      希望对你有所帮助~

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-10
        • 2010-12-14
        • 1970-01-01
        相关资源
        最近更新 更多