让android微调器显示多个项目

时间:2018-01-06 06:43:59

标签: android android-widget

如何让android widget spinner显示多个项目,如下所示,但只允许选择一个?

enter image description here

2 个答案:

答案 0 :(得分:0)

您要问的是微调器的默认行为。 以下是如何在微调器中设置多个值。

创建需要传递给微调器适配器的项目列表 并将其添加为Adapter中的最后一个参数。

    ArrayAdapter<String> adapter =
            new ArrayAdapter<String>(getApplicationContext(), R.layout.simple_spinner_dropdown_item, stringList);
    adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

可以获得如下选择的项目

   spinner.getSelectedItem().toString();

答案 1 :(得分:0)

将这些行粘贴到strings.xml中

<string-array name="country_arrays">
        <item>Malaysia</item>
        <item>United States</item>
        <item>Indonesia</item>
        <item>France</item>
        <item>Italy</item>
        <item>Singapore</item>
        <item>New Zealand</item>
        <item>India</item>
    </string-array>

在xml中使用以下行

<Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/country_arrays"
        android:prompt="@string/country_prompt" />

在您的活动或片段中使用以下行

public class MyAndroidAppActivity extends Activity {

  private Spinner spinner1;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    spinner1 = (Spinner) findViewById(R.id.spinner1);
    spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
  }
}

适配器类

public class CustomOnItemSelectedListener implements OnItemSelectedListener {

  public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
    Toast.makeText(parent.getContext(),
        "OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
        Toast.LENGTH_SHORT).show();
  }

  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub
  }

}

在我的情况下,我使用了字符串资源,你也可以传递一个列表

相关问题