12

我使用此处答案中的第二个选项向我的 ActionBar 添加了一个微调器。

如何向微调器添加微调器适配器?我尝试使用谷歌在此处描述的 Spinner 对象,但得到一个空 Spinner 对象。

有人知道怎么做吗?我不希望微调器位于操作栏的导航区域中,而是与其他操作项一起(我正在使用拆分操作栏)。

谢谢您的帮助!

4

4 回答 4

33

我知道这是一个老问题,但以防万一有人偶然发现它(就像我一样)并且仍然在寻找完整的答案,这里是如何使用兼容性库来做到这一点,以便它从 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

瞧!

于 2014-04-07T00:22:26.733 回答
15

我知道你放弃了微调器,但我会在这里给出一些提示,以防其他人遇到同样的问题,或者你在不同的应用程序中开发相同的模式

  • 如果你得到 null 是因为你没有正确指定 ID。仔细检查 ID。
  • 在您通过指定只是一个微调器的 actionLayout 来显示复杂内容的链接中,您只需指定一个 actionViewClass="android.widget.Spinner" 就可以了。
  • 然后在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
    

快乐的编码...

于 2012-07-30T11:38:32.443 回答
6

好吧,我放弃了使用子菜单的 Spinner 想法。我意识到微调器是用于选择保持选中状态的东西。子菜单接缝以更好地适应 UI。

于 2012-07-10T07:47:42.317 回答
-1
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
于 2015-03-23T12:20:23.367 回答