我需要将自定义Spinner下拉列表添加到我的操作栏。在主要活动中我使用以下代码。
private Toolbar mToolbar;
private Spinner mToolbarSpinner;
private List<SpinnerNavItem> mToolbarSpinnerNavigationItems;
private BaseAdapter mArrayAdapter;
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
/*Setup a Spinner*/
mToolbarSpinner = (Spinner) findViewById(R.id.spinner_toolbar);
/*Manage the spinner*/
mToolbarSpinnerNavigationItems = new ArrayList<SpinnerNavItem>();
mToolbarSpinnerNavigationItems.add(new SpinnerNavItem("Local", R.drawable.deviceonline,"device namne1","port",false));
mToolbarSpinnerNavigationItems.add(new SpinnerNavItem("My Places", R.drawable.deviceonline,"device name2","port2",false));
mArrayAdapter = new ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item,
mToolbarSpinnerNavigationItems);
mToolbarSpinner.setAdapter(mArrayAdapter);
当我运行项目时,我得到了以下输出
我该如何解决这个问题?
答案 0 :(得分:1)
您有两种选择:
首先,您可以覆盖类toString()
的方法SpinnerNavItem
,以返回您想要显示的内容。
其次,您可以覆盖getView()
的方法getDropDownView()
和ArrayAdapter
,以准确显示您想要的内容。
getView()
显示Spinner
上当前所选项目的文字(当前显示Spinner
的文字) getDropDownView()
显示Spinner
mArrayAdapter = new ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item,
mToolbarSpinnerNavigationItems) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
SpinnerNavItem currentItem = mToolbarSpinnerNavigationItems.get(position);
// remember to inflate custom layout for spinner item
// then set anything you want here
// remember to use convertView.findViewById(), not just findViewById()
// this is an example
// inflate layout
convertView = View.inflate(MainActivity.this, R.layout.support_simple_spinner_dropdown_item, null);
// get view
TextView tvText1 = (TextView) convertView.findViewById(android.R.id.text1);
// set content
tvText1.setText("Text to display");
// return
return convertView;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
// implement the same way as getView() method
}
};