如何在Android中向微调器添加项目?


Answers:


144

XML档案:

<Spinner
    android:id="@+id/Spinner01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

Java文件:

public class SpinnerExample extends Activity {

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

        String[] arraySpinner = new String[] {
            "1", "2", "3", "4", "5", "6", "7"
        };
        Spinner s = (Spinner) findViewById(R.id.Spinner01);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, arraySpinner);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s.setAdapter(adapter);
    }
}

请参阅微调器示例


7
尽管从理论上讲这可以回答问题,但最好在此处包括答案的基本部分,并提供链接以供参考。
比尔蜥蜴2012年

使用此android.R.layout.simple_spinner_dropdown_item代替此android.R.layout.simple_spinner_item看起来好多了
sai Gorantla 2014年

什么是array_spinner?数组的名称是arraySpinner。是拼写错误还是仅是这样?
SurajS 2015年

1
考虑增加adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);(前s.setAdapter(adapter);使下拉更好看。
禁令,地球工程

1
@StephenM更改了链接
pankajagarwal

99

我找到了另一个选择:布局文件中的微调器定义

<Spinner android:id="@+id/spinner"
    android:layout_width="fill_parent"
    android:drawSelectorOnTop="true"
    android:prompt="@string/spin"
    android:entries="@array/spinnerItems"
/>

文件array.xml中的项目定义:

<resources>
    <string-array name="spinnerItems">
        <item>item1</item>
        <item>item2</item>
        <item>item3</item>
        <item>item4</item>
    </string-array>
</resources>

链接到完整的代码源


我尝试了上面的所有方法以及其他一些教程,但这是唯一对我有用的方法。非常感谢!
snapplex 2014年

很高兴为您提供@snapplex;)
maxivis 2014年

1
这应该是最佳答案。清洁。

30

试试这个代码:

final List<String> list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
list.add("Item 5");

final String[] str = {"Report 1", "Report 2", "Report 3", "Report 4", "Report 5"};

final Spinner sp1 = (Spinner) findViewById(R.id.spinner1);
final Spinner sp2 = (Spinner) findViewById(R.id.spinner2);

ArrayAdapter<String> adp1 = new ArrayAdapter<String>(this,
                              android.R.layout.simple_list_item_1, list);
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(adp1);

ArrayAdapter<String> adp2 = new ArrayAdapter<String>(this,
                                  android.R.layout.simple_spinner_item, str);
adp2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(adp2);

sp1.setOnItemSelectedListener(new OnItemSelectedListener()
    {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            // TODO Auto-generated method stub
            Toast.makeText(getBaseContext(), list.get(position), Toast.LENGTH_SHORT).show();
        }

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

sp2.setOnItemSelectedListener(new OnItemSelectedListener()
    {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            // TODO Auto-generated method stub
            Toast.makeText(getBaseContext(), str[position], Toast.LENGTH_SHORT).show();
        }

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

您还可以通过String数组xml文件添加微调项值。

<resources>
    <string name="app_name">Spinner_ex5</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
    <string-array name="str2">
        <item>Data 1</item>
        <item>Data 2</item>
        <item>Data 3</item>
        <item>Data 4</item>
        <item>Data 5</item>
    </string-array>
</resources>

在mainActivity.java中:

final Spinner sp3 = (Spinner) findViewById(R.id.spinner3);
ArrayAdapter<CharSequence> adp3 = ArrayAdapter.createFromResource(this,
                                    R.array.str2, android.R.layout.simple_list_item_1);

adp3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp3.setAdapter(adp3);
sp3.setOnItemSelectedListener(new OnItemSelectedListener()
    {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            // TODO Auto-generated method stub
            String ss = sp3.getSelectedItem().toString();
            Toast.makeText(getBaseContext(), ss, Toast.LENGTH_SHORT).show();
        }

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

9

要在Spinner中添加项目,您可以做一件事,尝试创建适配器,然后将项目添加/删除到适配器中,然后可以使用setAdapter()方法轻松地将该适配器绑定到Spinner 。

这是一个例子:

spinner.setAdapter(adapter);
adapter.add(item1);
adapter.add(item2);
adapter.add(item3);
adapter.add(item4);
adapter.add(item5);
adapter.notifyDataSetChanged();
spinner.setAdapter(adapter);

thanx为您的答复我也得到了解决方案,现在我也面临一个问题。

我想获取微调器的选定项,即其位置,因为我想将其传递给其他方法,看看我做了什么... dataspin.setOnItemSelectedListener(new myitemlistener());

dataspin是我的微调对象

@Override public void onItemSelected(AdapterView <?> parent,View view,int position,long id){// TODO自动生成的方法存根String p = parent.getItemAtPosition(position).toString(); int pos =(int)parent.getItemIdAtPosition(position); System.out.println(“微调器的位置...” + pos); setSearchView(pos); }

如果我这样做不是微调项目不显示

8
<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>

在您的布局中:

<Spinner 
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:entries="@array/array_name"
    />

但是您如何获得所选项目?
灰心

1
Java文件中的第一个TypeCast。然后使用Spinner spinner; spinner = findViewById(R.id.spinner); spinner.setOnItemClickListener(new AdapterView.OnItemClickListener(){@Override public void onItemClick(AdapterView <?> parent,View view,int position,long id){}});
ZIA ANSARI

5

这段代码基本上读取JSON数组对象,并将每一行转换为微调器中作为参数传递的选项:

public ArrayAdapter<String> getArrayAdapterFromArrayListForSpinner(ArrayList<JSONObject> aArrayList, String aField)
{
    ArrayAdapter<String> aArrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item);
    aArrayAdapter.setDropDownViewResource(R.layout.multiline_spinner_dropdown_item); //android.R.layout.simple_spinner_dropdown_item
    try {
        for (int i = 0; i < aArrayList.size(); i++)
        {
            aArrayAdapter.add(aArrayList.get(i).getString(aField)); 
        }
    } catch (JSONException e) {
        e.printStackTrace();
        ShowMessage("Error while reading the JSON list");
    }
    return aArrayAdapter;       
}

2

将微调器添加到XML布局,然后将此代码添加到Java文件:

Spinner spinner;
spinner = (Spinner) findViewById(R.id.spinner1) ;
java.util.ArrayList<String> strings = new java.util.ArrayList<>();
strings.add("Mobile") ;
strings.add("Home");
strings.add("Work");
SpinnerAdapter spinnerAdapter = new SpinnerAdapter(AddMember.this, R.layout.support_simple_spinner_dropdown_item, strings);
spinner.setAdapter(spinnerAdapter);

1

更新列表后添加此代码

假设:

ArrayAdapter <String>变量名是dataAdapter,而List变量名是keys

  • dataAdapter.addAll(keys);
  • dataAdapter.notifyDataSetChanged();

1

要将其他项目添加到Spinner中,您可以:

ArrayAdapter myAdapter = 
  ((ArrayAdapter) mySpinner.getAdapter());

myAdapter.add(myValue);

myAdapter.notifyDataSetChanged();

发生“ UnsupportedOperationException”
abbasalim

0

只是清除适配器,添加所有itens并通知更改,如下所示:

  public void show(List<Object> objLIst) {
    adapter.clear();
    adapter.addAll(objLIst);
    adapter.notifyDataSetChanged(); }

0

一种更简单的方法是使用材料微调器库:https : //github.com/jaredrummler/MaterialSpinner

首先添加到您的项目:

compile 'com.jaredrummler:material-spinner:1.2.4'

并像这样使用:

<com.jaredrummler.materialspinner.MaterialSpinner
    android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

和Java代码,您可以轻松地在Java中添加项目:

MaterialSpinner spinner = (MaterialSpinner) findViewById(R.id.spinner);
spinner.setItems("item 1", "item 2", "item 3", "item 4", "item 5");
spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {

  @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
    Snackbar.make(view, "Clicked " + item, Snackbar.LENGTH_LONG).show();
  }
});
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.