Button根據EditText輸入狀態改變背景顏色
需求
Button隨EditText輸入狀態改變顏色
有3個不同顏色狀態,
+ EditText未輸入時,Button處於不可點選狀態
+ EditText輸入時,Button處於高亮狀態
+ EditText輸入且使用者按下按鈕,Button –> Pressed狀態
效果如下:
EditText在沒有輸入時,Button不可點選,為灰色狀態
EditText輸入後,Button可點選,且背景變為藍色
EditText輸入後,點選Button時,Button背景色變為紅色
解決思路
EditText的輸入通過新增addTextChangedListener來監聽
Button的點選顏色變化使用selector來控制
遇到的問題
在根據以上的實現思路實現時,遇到了一些問題
問題一:在Selector中使用android:color屬性報錯
button_selector.xml程式碼:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@android:color/holo_red_light" android:state_pressed="true"/>
<item android:color="@android:color/darker_gray" />
</selector>
應用崩潰的錯誤日誌:
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #0: <item> tag requires a 'drawable' attribute or child tag defining a drawable
日誌提示在item子節點中必須要求有drawable
屬性,根據錯誤資訊將所有color
屬性替換成了drawable
,修改後的button_selector.xml如下:
<selector xmlns:android ="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/holo_red_light" android:state_pressed="true"/>
<item android:drawable="@android:color/darker_gray"/>
</selector>
問題二:selector沒有作用,Button按下時顏色並沒有改變
給Button的background屬性設定了button_selector
然後在EditText. addTextChangedListener中的onTextChanged方法中檢測EditText的輸入狀態
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//EditText輸入狀態改變,Button背景顏色也改變
if ("".equals(editText.getText().toString().trim())) {
button.setBackgroundColor(Color.GRAY);
button.setEnabled(false);
} else {
button.setBackgroundColor(ContextCompat.getColor(context, R.color.color_blue));
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
在EditText中輸入字元後,Button背景色變為藍色,但是pressed時卻沒有變成紅色,背景還是藍色,發現是button.setBackgroundColor(ContextCompat.getColor(context, R.color.color_blue));
把Button的背景色給寫死了,所以Button的顏色沒辦法改變
解決方案
整理了下問題,最後想到了一個解決方案,在佈局檔案中,把Button的background的屬性由selector設定為不可點選顏色灰色android:background="@android:color/darker_gray"
,然後在onTextChanged()中,當EditText輸入時,設定Button的background為selector,而不是寫死顏色,這樣就可以解決在EditText輸入時,點選Button背景顏色卻無法變化的問題!
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//EditText輸入狀態改變,Button背景顏色也改變
if ("".equals(editText.getText().toString().trim())) {
button.setBackgroundColor(Color.GRAY);
button.setEnabled(false);
} else {
//設定selector來控制Button背景顏色
button.setBackground(ContextCompat.getDrawable(context,
R.drawable.button_input_selector));
button.setEnabled(true);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});