menuitem - 开关未显示在ActionBar上

时间:2017-09-06 11:46:48

标签: java android xml

我想在主菜单的操作栏上打开一个开关。空的空间在那里我可以点击它,但没有开关。什么可以解决方案?

提前致谢!

switch_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/switchView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

<android.support.v7.widget.SwitchCompat
    android:id="@+id/switchForActionBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""/>

activtiy_main_action.xml:

<item
    android:id="@+id/myswitch"
    android:title=""
    app:showAsAction="always"
    android:actionLayout="@layout/switch_layout">
</item>

MainActivity.java

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuinf = getMenuInflater();
    menuinf.inflate(R.menu.activity_main_action, menu);
    //getMenuInflater().inflate(R.menu.mainmenu, menu);

    return super.onCreateOptionsMenu(menu);
}

1 个答案:

答案 0 :(得分:2)

在菜单中更改此内容

使用 app:actionLayout="@layout/switch_layout"

insted of android:actionLayout="@layout/switch_layout"

<item
    android:id="@+id/myswitch"
    android:title=""
    app:showAsAction="always"
    app:actionLayout="@layout/switch_layout">
</item>

并且访问您的交换机使用以下代码

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.badge_menu, menu);
    MenuItem item = menu.findItem(R.id.myswitch);
    MenuItemCompat.setActionView(item, R.layout.switch_layout);
    RelativeLayout notifCount = (RelativeLayout) MenuItemCompat.getActionView(item)

    Switch switch_button = (Switch) notifCount.findViewById(R.id.switchForActionBar);

    switch_button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // do something, the isChecked will be
            // true if the switch is in the On position
        }
    });
    return super.onCreateOptionsMenu(menu);
}