//-------------------------------------------静态的Spinner,弹出的列表框只显示内容-------------------------------------------
1.定义成员变量
private static final String[] countriesStr = { "台北市", "台北县", "台中市", "高雄市" };
private Spinner mySpinner; //下拉列表
private ArrayAdapter adapter; //数组
2.创建
mySpinner = (Spinner) findViewById(R.id.mySpinner); //
adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, countriesStr);
//myspinner_dropdown为自定义下拉菜单样式定义在res/layout目录下
adapter.setDropDownViewResource(R.layout.myspinner_dropdown);
//将ArrayAdapter加入Spinner对象中
mySpinner.setAdapter(adapter);
3.监听
//将mySpinner加入OnItemSelectedListener
mySpinner
.setOnItemSelectedListener(new Spinner.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView arg0, View arg1,
int arg2, long arg3)
{
/* 将所选mySpinner的值带入myTextView中 */
myTextView.setText("选择的是" + countriesStr[arg2]);
/* 将mySpinner显示 */
arg0.setVisibility(View.VISIBLE);
}
@Override
public void onNothingSelected(AdapterView arg0)
{
// TODO Auto-generated method stub
}
});
资源:
<Spinner
android:id="@+id/mySpinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</Spinner>
myspinner_dropdown.xml
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="24sp"
android:singleLine="true"
style="?android:attr/spinnerDropDownItemStyle" />
//-------------------------------------------动态添加/删除的Spinner,弹出的列表框显示一个单选按钮-------------------------------------
android若要动态的增减Spinner的下拉菜单的选项,就要利用ArrayList来完成。
1.定义变量
private static final String[] countriesStr = { "台北市", "台北县", "台中市", "高雄市" };
private Spinner mySpinner;
private ArrayAdapter adapter;
private List allCountries;
2.创建动态数组,并赋值。
allCountries = new ArrayList();
for (int i = 0; i < countriesStr.length; i++)
{
allCountries.add(countriesStr[i]);
}
3.
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, allCountries);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
4.
mySpinner = (Spinner) findViewById(R.id.mySpinner);
mySpinner.setAdapter(adapter);
5.
mySpinner
.setOnItemSelectedListener(new Spinner.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView arg0, View arg1,
int arg2, long arg3)
{
//将所选mySpinner的值带入myTextView中
myTextView.setText(arg0.getSelectedItem().toString());
}
@Override
public void onNothingSelected(AdapterView arg0)
{
}
});
6.添加内容
//将值新增至adapter
adapter.add(newCountry);
//取得新增的值的位置
int position = adapter.getPosition(newCountry);
//将Spinner选取在新增的值的位置
mySpinner.setSelection(position);
7.移除选中的内容
adapter.remove(mySpinner.getSelectedItem().toString());
下拉列表框spinner
最新推荐文章于 2024-06-09 04:43:27 发布