Android-Spinner下拉列表Demo

技术分享

代码

package com.lxt008;

import com.lxt008.R;

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

public class Activity01 extends Activity
{
    private static final String[]    m_Countries    = { "O型", "A型", "B型", "AB型", "其他" };

    private TextView                m_TextView;
    private Spinner                    m_Spinner;
    private ArrayAdapter<String>    adapter;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        m_TextView = (TextView) findViewById(R.id.TextView1);
        m_Spinner = (Spinner) findViewById(R.id.Spinner1);

        //将可选内容与ArrayAdapter连接
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, m_Countries);

        //设置下拉列表的风格
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        //将adapter添加到m_Spinner中
        m_Spinner.setAdapter(adapter);

        //添加Spinner事件监听
        m_Spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
            {
                m_TextView.setText("你的血型是:" + m_Countries[arg2]);
                //设置显示当前选择的项
                arg0.setVisibility(View.VISIBLE);
            }

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

        });
    }
}

 

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:id="@+id/TextView1"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<Spinner
  android:id="@+id/Spinner1"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_centerHorizontal="true"
/>
</LinearLayout>

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。