20 Android Spinner

package com.spinner.test;

import com.spinner.test.R.string;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class SpinnerActivity extends Activity  {
    /** Called when the activity is first created. */
	private Spinner spinner;
	private ArrayAdapter<CharSequence> adapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        spinner=(Spinner)findViewById(R.id.spinner1);
        adapter=ArrayAdapter.createFromResource(this, R.array.cityName, android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				String str=(String)spinner.getItemAtPosition(arg2);
				Toast.makeText(SpinnerActivity.this, str, Toast.LENGTH_SHORT).show();
				
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
    }
	
		
}
第二种
package com.example.spinnertest;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.widget.ArrayAdapter;import android.widget.Spinner;public class MainActivity extends Activity { private Spinner spinner; private ArrayAdapter<CharSequence> adapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);spinner=(Spinner)findViewById(R.id.spinner1);adapter=ArrayAdapter.createFromResource(this, R.array.cityName, android.R.layout.simple_spinner_dropdown_item);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">SpinnerTest</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>

    <string-array name="cityName">
        <item>北京</item>
        <item>上海</item>
        <item >深圳</item>
        <item >广州</item>
    </string-array>

</resources>



你可能感兴趣的:(20 Android Spinner)