android输入时背景颜色,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代碼:
應用崩潰的錯誤日志:
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #0: tag requires a 'drawable' attribute or child tag defining a drawable
日志提示在item子節點中必須要求有drawable屬性,根據錯誤信息將所有color屬性替換成了drawable,修改后的button_selector.xml如下:
問題二: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) {
}
});
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的android输入时背景颜色,Button根据EditText输入状态改变背景颜色的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 你的电脑性能过时了吗你的电脑性能过时了吗
- 下一篇: android volley 上传图片