android 上拉菜单,Spinner上拉菜单

本文介绍了如何在Android中实现Spinner自定义下拉菜单,包括设置默认的下拉菜单样式,以及动态添加和删除选项的方法。通过创建ArrayAdapter,设置OnItemSelectedListener监听,可以实现菜单项的选择并显示选择内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spinner下拉菜单

一、Spinner自定义下拉菜单

private Spinner mySpinner;

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.spinner);

final String[] countriesStr = { "台北市", "台北县", "台中市", "高雄市" };

ArrayAdapter adapter = new ArrayAdapter(this,

R.layout.myspinner, R.id.textView1, countriesStr);

//默认:ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item,allCountries);

//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//右边有radio,可去掉_dropdown

mySpinner = (Spinner) findViewById(R.id.spinner1);

mySpinner.setAdapter(adapter);

mySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

public void onItemSelected(AdapterView> arg0, View arg1,

int arg2, long arg3) {

toast(countriesStr[arg2]);//toast(arg0.getSelectedItem().toString());

}

public void onNothingSelected(AdapterView> arg0) {

}

});

}

public void toast(String str) {

Toast.makeText(SpinnerNew.this, str, Toast.LENGTH_LONG).show();

}

myspinner.xml

xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:id="@+id/linearLayout1"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

android:layout_width="fill_parent"

android:id="@+id/linearLayout2"

android:layout_height="wrap_content"

android:background="@color/yellow">

android:id="@+id/imageView1"

android:src="@drawable/icon"

android:layout_width="wrap_content"

android:layout_height="wrap_content">

android:text="TextView"

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textColor="@color/black">

0224501749.png

0224501750.png

二、动态添加和删除选项

/* 将值新增至adapter */

String newCountry = "hello";

adapter.add(newCountry);

int position = adapter.getPosition(newCountry);

mySpinner.setSelection(position);

/* 将选中项从adapter移除 */

adapter.remove(mySpinner.getSelectedItem().toString());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值