android spinner 自定义下拉列表,android – 自定义Spinner在选择后不隐藏下拉菜单
(Android API版本9)我创建了一个带有自定义适配器的微调器,并覆盖了getView()以使用具有文本视图的xml文件对其进行充气.但是现在,我的微调器没有在用户选择项目后关闭下拉列表.无论如何在选择项目时关闭微调器下拉列表?码//Code in onCreate functionSpinner list = (Spinner) findViewById(R.id.spn_purchase
(Android API版本9)我创建了一个带有自定义适配器的微调器,并覆盖了getView()以使用具有文本视图的xml文件对其进行充气.但是现在,我的微调器没有在用户选择项目后关闭下拉列表.无论如何在选择项目时关闭微调器下拉列表?
码
//Code in onCreate function
Spinner list = (Spinner) findViewById(R.id.spn_purchaseList);
listAdapter = new ItemListAdapter(this, new MyItemList());
list.setAdapter(listAdapter);
listAdapter.item_list.addItem(new MyItem("Test", "Test Item"));
listAdapter.notifyDataSetChanged();
//onCreate end
//the class below is inside "MainActivity extends Activity"
class ItemListAdapter extends BaseAdapter
{
Context context;
MyItemList item_list;
MyItem selectedItem;
ItemListAdapter(Context con,MyItemList k)
{
super();
this.context=con;
this.item_list=k;
selectedItem=null;
}
@Override
public int getCount() {
return item_list.getCount();
}
@Override
public MyItem getItem(int arg0) {
return this.item_list.getList().get(arg0);
}
@Override
public long getItemId(int arg0) {
return this.item_list.getPosition(this.item_list.getList().get(arg0));
}
@Override
public View getView(int position, View arg1, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View spinner_item = inflater.inflate(R.layout.spinner_layout, parent, false);
TextView tx = (TextView)spinner_item.findViewById(R.id.txt_spinner);
tx.setId((int) item_list.getPosition(item_list.getList().get(position)));
tx.setText(this.item_list.getList().get(position).name.toString());
tx.setBackgroundResource(R.drawable.spinner_item);
tx.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectedItem = item_list.getItem(v.getId());
list.setSelection(v.getId());
}
});
return spinner_item;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
return getView(position,convertView,parent);
}
}
解决方法:
调用setVisibility(View.GONE)可以隐藏下拉列表,但它似乎会导致Spinner状态出现问题,即在关闭后您将无法重新打开下拉列表.
首选方法是获取Spinner的句柄并从onClick()侦听器调用它的onDetachedFromWindow().
@Override
public void onClick(View v) {
// code here to get selected item and do something with it
// hide the spinner dropdown
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
if (spinner != null) {
try {
Method method = Spinner.class.getDeclaredMethod("onDetachedFromWindow");
method.setAccessible(true);
method.invoke(spinner);
} catch (Exception e) {
e.printStackTrace();
}
}
}
标签:android,android-spinner
来源: https://codeday.me/bug/20190708/1407177.html
更多推荐
所有评论(0)