繁体   English   中英

选项项目选定状态时更改背景颜色

[英]Options Item Selected change background color when state pressed

在下图中,我的菜单项状态被“按下”时,我想更改背景颜色:

枫树

那么如何实现呢?

我的菜单:

<?xml version="1.0" encoding="utf-8"?>

<item android:id="@+id/detail_edit_item"
      android:title="@string/edit"
      android:icon="@drawable/ic_edit_white"
      app:showAsAction="always"/>

<item android:id="@+id/detail_delete_item"
      android:title="@string/delete"
      android:icon="@drawable/ic_delete_white"
      app:showAsAction="always"/>

您可以使用以下解决方法:对于API级别11或更高版本,可以使用工具栏小部件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.test.myapplication.MainActivity">
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Titel"
            android:layout_alignParentLeft="true" />
        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/background_selector"
            android:layout_alignParentRight="true"
            />
    </RelativeLayout>
</android.support.v7.widget.Toolbar>

要使用此工具栏,必须为活动设置NoActionBarTheme

<activity android:name=".MainActivity"
    android:theme="@style/Theme.AppCompat.NoActionBar">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

在此示例中,我仅使用了带有自定义删除按钮的ImageButton,之后可以编写选择器来处理按钮按下,如下所示:

<?xml version="1.0" encoding="utf-8"?>

<item android:drawable="@drawable/delete" android:state_selected="true"></item>
<item android:drawable="@drawable/delete" android:state_pressed="true"></item>
<item android:drawable="@drawable/delete_not_selected"></item>

您可以将此代码保存在drawable文件夹下,作为background_selector.xml,这应该可以正常工作。 您可以在下面找到两个图像,但是delete_not_selected是白色的,因此不可见,但是您仍然可以通过单击Delete按钮的右侧来下载它。

删除 delete_not_selected

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM