how to add item to Spinner's ArrayAdapter?

Posted by allen-c on Stack Overflow See other posts from Stack Overflow or by allen-c
Published on 2010-03-24T03:45:03Z Indexed on 2010/03/24 3:53 UTC
Read the original article Hit count: 736

Filed under:
|
|
|

i had a EditText , a button and a spinner . When click the button , the spinner will add a new item with name you entered in the EditText. But here is the question, my adapter.add() method seems doesn't work...here is my code:

public class Spr extends Activity {
Button bt1;
EditText et;
ArrayAdapter<CharSequence> adapter;
Spinner spinner;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    bt1 = (Button)this.findViewById(R.id.bt1);
    et = (EditText)this.findViewById(R.id.et);  
    spinner = (Spinner)this.findViewById(R.id.spr);

    adapter = ArrayAdapter.createFromResource(
            this, R.array.planets_array, android.R.layout.simple_spinner_item);

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner.setAdapter(adapter);

    bt1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String temp = et.getText().toString();

            adapter.add(temp);
            adapter.notifyDataSetChanged();
            spinner.setAdapter(adapter);

        }
    });


    spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int pos, long id) {

            Toast.makeText(parent.getContext(), "The planet is " +
                      parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {

        }});
}

}

© Stack Overflow or respective owner

Related posts about adapter

Related posts about android