Android下拉框制作

下拉列表 Spinner的一个简单实例:
SpinnerActivity:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class SpinnerActivity extends Activity implements OnClickListener{
//定义控件
private TextView show;
private Spinner spinner;
private String[] provices;

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);

//获取控件
spinner=(Spinner)findViewById(R.id.mySpinner);
provices=getResources().getStringArray(R.array.provice);
show=(TextView)findViewById(R.id.showSpinnerContent);
//按钮触发函数
findViewById(R.id.btnGetSpinnerContent).setOnClickListener(this);
//ArrayAdapter
ArrayAdapter<String> adapter=new 
ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item , 
provices);
spinner.setAdapter(adapter);
//Item发放
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){


@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
show.setText(provices[arg2]);
}


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


@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnGetSpinnerContent:
int index=spinner.getSelectedItemPosition();
Toast.makeText(this,provices[index], Toast.LENGTH_LONG).show();
break;
default:
break;
}

}


}
XML代码:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    <Spinner 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/mySpinner"/>
    
    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/showSpinnerContent"
        android:layout_below="@id/mySpinner"
        android:layout_marginTop="30dp"/>
    
    <Button 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/showSpinnerContent"
        android:text="获取下拉框的值"
        android:id="@+id/btnGetSpinnerContent"
        android:layout_marginTop="30dp"/>
    


</RelativeLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值