自定义微调器,最后一项作为链接

时间:2014-09-16 10:11:17

标签: android spinner

我希望Spinner包含最后Item作为"添加更多项目" 当我点击它,然后我可以添加下一个项目。我添加的项目应显示在微调器列表中,并且与#34相同的最后一项;添加更多项目" .. 我尝试使用Adapter,但如何将最后一个元素保留为"添加更多项目"

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position == spinner.getItemIdAtPosition(spinner.getCount()))
                // my code for adding item to list using Adapter
            else
                // spinner.setSelection();
        }

我写错了什么? 任何帮助??谢谢...

1 个答案:

答案 0 :(得分:0)

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

           <Spinner
            android:id="@+id/spinner1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:dropDownVerticalOffset="2dp"
            android:dropDownWidth="500sp"
            android:spinnerMode="dropdown" />


    </RelativeLayout>

MainActivity.java:

public class MainActivity extends Activity {

    private Spinner spinner;

    ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ArrayList<String> data = new ArrayList<String>();

        for (int i = 0; i < 5; i++) {
            data.add("item " + i);
        }
        data.add("Add New Item");

        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, data);
        spinner = (Spinner) findViewById(R.id.spinner1);
        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                tv.setText(spinner.getSelectedItem().toString());

                if (spinner.getSelectedItem().toString().equals("Add New Item")) {

                    data.remove(position);
                    data.add(position, "item " + position);
                    data.add((position + 1), "Add New Item");

                    updateAdapter(data);

                    Toast.makeText(getApplicationContext(), "item " + position,
                            Toast.LENGTH_LONG).show();
                }

            }

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

            }
        });

    }

    public void updateAdapter(ArrayList<String> data) {

        adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,
                data);
        adapter.notifyDataSetChanged();

    }

}