如何在后台使用可绘制资源

时间:2020-10-20 16:48:10

标签: android drawable

我尝试在按钮上使用drawable,但是它不起作用

我该怎么办?

button_enable.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:color="#FF0000FF"/>
    <item android:state_enabled="false" android:color="#440000FF"/>
</selector>

activity_main.xml

<EditText
    android:id="@+id/et1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="input email"/>
<Button
    android:id="@+id/btn1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="OK"
    android:textColor="#FFFFFF"
    android:background="@drawable/button_enable"/>

MainActivity.java

et1.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }
    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if(et1.length()>0)
            btn1.setEnabled(true);
        else
            btn1.setEnabled(false);
    }
    @Override
    public void afterTextChanged(Editable editable) {
     }
});

2 个答案:

答案 0 :(得分:1)

您需要使用android:color="#FF0000FF"

而不是在项目内使用android:drawable

,您需要创建一个具有目标背景的可绘制对象。

所以会像

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@drawable/button_bg_press" />
<item android:state_focused="true" android:drawable="@drawable/button_bg_press" />
<item android:state_pressed="true" android:drawable="@drawable/button_bg_press"  />

和背景可绘制对象,例如:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
<solid android:color="#FF4081"/>
</shape>

答案 1 :(得分:0)

您使用了错误的状态。这些状态适用于切换台。要查看按钮上的颜色效果,请尝试使用此按钮。

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#FF0000FF"/>
    <item android:state_pressed="false" android:color="#440000FF"/>
</selector>