更改用户单击时可绘制的MenuItem

时间:2018-08-05 12:34:27

标签: java android android-layout android-menu

所以我有以下配置:
一个带有选择器可绘制附件的MenuItem,我想根据用户单击来更改它。
但是由于某种原因,我无法使它正常工作,因为我无法找到一种比较图标(可绘制对象)的方法。 我的配置如下:

    <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/menu_grid_id"
        android:icon="@drawable/grid_option"
        android:title="@string/layout_type"
        app:showAsAction="ifRoom" />

</menu>

选择器附在下面:

<?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:drawable="@drawable/ic_grid_on_32" 
          android:state_pressed="true" />
       <item android:drawable="@drawable/ic_grid_off_32" /> <!-- default -->
    </selector>

还有onOptionsItemSelected:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.menu_grid_id: {
            //I tried to use getContentState but does not seem to be reliable.   
        }
        default:
            return true;
    }

}

1 个答案:

答案 0 :(得分:0)

我最终回答了自己的问题。也许它将帮助其他有相同问题的人。
这个想法相对简单(如果您知道的话),它是使用开关或切换按钮。
选项菜单如下所示:

    <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/menu_grid_id"
        android:title="@string/layout_type"
        // that was the difference
        app:actionLayout="@layout/grid_option_layout"
        app:showAsAction="ifRoom" />

</menu>

现在,可以使用ToggleButton或Switch。我最终使用了ToggleButton。下面是一个可以配置的文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ToggleButton
        android:id="@+id/switch_grid"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_centerVertical="true"
        android:background="@drawable/grid_option"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:textOff=""
        android:textOn="" />
</RelativeLayout>

现在,可绘制选择器如下所示(grid_option):

    <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_grid_on_32" android:state_checked="true" />
    <item android:drawable="@drawable/ic_grid_off_32" /> <!-- default -->
</selector>

当然,ic_grid_on和off是一些图像。