鸟语天空
基本视图——Spinner
post by:追风剑情 2015-9-7 21:49

一、配置strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="presidents_array">
        <item>John F. Kennedy</item>
        <item>Lyndon B. Johnson</item>
        <item>Richard Nixon</item>
        <item>Gerald Ford</item>
        <item>Jimmy Carter</item>
        <item>Ronald Reagan</item>
        <item>George H. W. Bush</item>
        <item>Bill Clinton</item>
        <item>George W. Bush</item>
        <item>Barack Obama</item>
    </string-array>
</resources>

视图

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true" />
</LinearLayout>

代码

package com.example.androidtest;

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 {

	String[] presidents;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_spinner);
		
		presidents = getResources().getStringArray(R.array.presidents_array);
		Spinner s1 = (Spinner) findViewById(R.id.spinner1);
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
				android.R.layout.simple_spinner_item, presidents);
		//下接列表显示为单选按钮
		/*ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
				android.R.layout.simple_list_item_single_choice, presidents);*/
		
		s1.setAdapter(adapter);
		s1.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				int index = parent.getSelectedItemPosition();
				Toast.makeText(getBaseContext(), "You have selected item : "+presidents[index], 
						Toast.LENGTH_SHORT).show();
			}

			/**
			 * 当用户按下Back按钮时触发这一方法,撤销所显示的项列表。
			 * 在这种情况下,没有任何项被选择,也不需要作任何处理。
			 */
			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}
			
		});
	}
}

运行效果

ssssssssssss.png

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容