Spinner

1.设置Spinner之中的元素内容,采用了ArrayAdapter来描述,并通过setApdater()来设置adapter

2.设置spinner展开的方式,这里通过设置ArrayAdapter的第二个参数,设置了spinner没有展开前的UI格式,simple_spinner_item是textview的label方式,而simple_spinner_dropdown_item这是点击圆圈选择方式。在这个例子中,我们将展开方式设置为点击圆圈选择

3.使用setOnItemSelectedListener()来设置Spinner的点击触发的callback函数,有onItemSelected和onNothingSelected两个接口需要具体给出。

 通过调用资源文件的array创建adapter

public class MainActivity extends Activity implements OnItemSelectedListener {
    private Spinner sp;
    private TextView tv;
    private ArrayAdapter<CharSequence> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sp = (Spinner) findViewById(R.id.spinner1);
        tv = (TextView) findViewById(R.id.textView1);
        adapter = ArrayAdapter.createFromResource(this, R.array.test,
                android.R.layout.simple_spinner_item);
        sp.setAdapter(adapter);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub
        tv.setText(sp.getItemAtPosition(arg2).toString());
    }

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

 

posted @ 2012-12-02 14:34  Mr.haox  阅读(422)  评论(0编辑  收藏  举报