我使用此处答案中的第二个选项向我的 ActionBar 添加了一个微调器。
如何向微调器添加微调器适配器?我尝试使用谷歌在此处描述的 Spinner 对象,但得到一个空 Spinner 对象。
有人知道怎么做吗?我不希望微调器位于操作栏的导航区域中,而是与其他操作项一起(我正在使用拆分操作栏)。
谢谢您的帮助!
我知道这是一个老问题,但以防万一有人偶然发现它(就像我一样)并且仍然在寻找完整的答案,这里是如何使用兼容性库来做到这一点,以便它从 v7(Android 2.1 Eclair)到当前 v19(Android 4.4 KitKat):
在 menu_layout.xml 中:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item android:id="@+id/spinner"
yourapp:showAsAction="ifRoom"
yourapp:actionViewClass="android.widget.Spinner" />
</menu>
使用http://schemas.android.com/apk/res-auto
命名空间别名 asyourapp
使您能够使用旧版本 Android 上不存在的属性 showAsAction 和 actionViewClass。
然后在您的活动代码中:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_layout, menu);
MenuItem item = menu.findItem(R.id.spinner);
Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
spinner.setAdapter(adapter); // set the adapter to provide layout of rows and content
spinner.setOnItemSelectedListener(onItemSelectedListener); // set the listener, to perform actions based on item selection
瞧!
我知道你放弃了微调器,但我会在这里给出一些提示,以防其他人遇到同样的问题,或者你在不同的应用程序中开发相同的模式
然后在OnCreateOptionsMenu
你做:
inflater.inflate(R.menu.my_menu, menu); // inflate the menu
Spinner s = (Spinner) menu.findItem(R.id.my_menu_spinner).getActionView(); // find the spinner
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(getActivity().getActionBar()
.getThemedContext(), R.array.my_menu_spinner_list, android.R.layout.simple_spinner_dropdown_item); // create the adapter from a StringArray
s.setAdapter(mSpinnerAdapter); // set the adapter
s.setOnItemSelectedListener(myChangeListener); // (optional) reference to a OnItemSelectedListener, that you can use to perform actions based on user selection
快乐的编码...
好吧,我放弃了使用子菜单的 Spinner 想法。我意识到微调器是用于选择保持选中状态的东西。子菜单接缝以更好地适应 UI。
inflater.inflate(R.menu.my_menu, menu); // inflate the menu
Spinner s = (Spinner) menu.findItem(R.id.my_menu_spinner).getActionView(); // find the spinner
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(getActivity().getActionBar() .getThemedContext(), R.array.my_menu_spinner_list, android.R.layout.simple_spinner_dropdown_item); // create the adapter from a StringArray
s.setAdapter(mSpinnerAdapter); // set the adapter
s.setOnItemSelectedListener(myChangeListener); // (optional) reference to a OnItemSelectedListener, that you can use to perform actions based on user selection