Android:更改按钮文本和背景颜色 [英] Android : change button text and background color

查看:38
本文介绍了Android:更改按钮文本和背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在按下按钮时使用 xml 更改文本和背景颜色?

How can I change both text and background colors when my button is pressed, with xml ?

要更改文本颜色,我可以这样做:

To change text color I can do :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="mycolor"/>
    <item android:color="mycolor2"/>
</selector>

要更改我可以做的背景(在具有可绘制参考的选择器/项目中使用它):

To change the background I can do (using it in a selector/item with drawable reference) :

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FF0079FF" />
</shape>

但是我怎样才能做到这两点呢?假设我想要:

But how can I do both ? Let's say I want to have :

  • 默认:黑色文本/白色背景
  • 按下:白色文字/蓝色背景

我完全忘记了背景和文本颜色是分开管理的,所以我是这样做的:

I totaly forgot that the background and text color are managed separately, so this is how I did it :

<Button
    android:textColor="@color/filtersbuttoncolors"
    android:background="@drawable/mybackgroundcolors" />

在 mybackgroundcolors.xml 中我管理背景,在 filtersbuttoncolors.xml 中我管理文本颜色.在这两个 xml 文件中,我管理状态(按下、选择、默认)

In mybackgroundcolors.xml I manage the background and in filtersbuttoncolors.xml I manage the text color. In both xml files I manage the status (pressed, selected, default)

推荐答案

这是一个默认情况下为白色的 drawable 示例,按下时为黑色:

Here is an example of a drawable that will be white by default, black when pressed:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid
                android:color="#1E669B"/>
            <stroke
                android:width="2dp"
                android:color="#1B5E91"/>
            <corners
                android:radius="6dp"/>
            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp"/>
        </shape>

    </item>
    <item>
        <shape>
            <gradient
                android:angle="270"
                android:endColor="#1E669B"
                android:startColor="#1E669B"/>
            <stroke
                android:width="4dp"
                android:color="#1B5E91"/>
            <corners
                android:radius="7dp"/>
            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp"/>
        </shape>
    </item>
</selector>

这篇关于Android:更改按钮文本和背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆