android输入时背景颜色,Button根据EditText输入状态改变背景颜色
需求
Button隨EditText輸入狀態(tài)改變顏色
有3個(gè)不同顏色狀態(tài),
EditText未輸入時(shí),Button處于不可點(diǎn)擊狀態(tài)
EditText輸入時(shí),Button處于高亮狀態(tài)
EditText輸入且用戶按下按鈕,Button --> Pressed狀態(tài)
效果如下:
演示圖片
EditText在沒有輸入時(shí),Button不可點(diǎn)擊,為灰色狀態(tài)
EditText輸入后,Button可點(diǎn)擊,且背景變?yōu)樗{(lán)色
EditText輸入后,點(diǎn)擊Button時(shí),Button背景色變?yōu)榧t色
解決思路
EditText的輸入通過添加addTextChangedListener來監(jiān)聽
Button的點(diǎn)擊顏色變化使用selector來控制
遇到的問題
在根據(jù)以上的實(shí)現(xiàn)思路實(shí)現(xiàn)時(shí),遇到了一些問題
問題一:在Selector中使用android:color屬性報(bào)錯(cuò)
button_selector.xml代碼:
應(yīng)用崩潰的錯(cuò)誤日志:
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #0: tag requires a 'drawable' attribute or child tag defining a drawable
日志提示在item子節(jié)點(diǎn)中必須要求有drawable屬性,根據(jù)錯(cuò)誤信息將所有color屬性替換成了drawable,修改后的button_selector.xml如下:
問題二:selector沒有作用,Button按下時(shí)顏色并沒有改變
給Button的background屬性設(shè)置了button_selector
然后在EditText. addTextChangedListener中的onTextChanged方法中檢測EditText的輸入狀態(tài)
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輸入狀態(tài)改變,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背景色變?yōu)樗{(lán)色,但是pressed時(shí)卻沒有變成紅色,背景還是藍(lán)色,發(fā)現(xiàn)是button.setBackgroundColor(ContextCompat.getColor(context, R.color.color_blue));把Button的背景色給寫死了,所以Button的顏色沒辦法改變
解決方案
整理了下問題,最后想到了一個(gè)解決方案,在布局文件中,把Button的background的屬性由selector設(shè)置為不可點(diǎn)擊顏色灰色android:background="@android:color/darker_gray",然后在onTextChanged()中,當(dāng)EditText輸入時(shí),設(shè)置Button的background為selector,而不是寫死顏色,這樣就可以解決在EditText輸入時(shí),點(diǎn)擊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輸入狀態(tài)改變,Button背景顏色也改變
if ("".equals(editText.getText().toString().trim())) {
button.setBackgroundColor(Color.GRAY);
button.setEnabled(false);
} else {
//設(shè)置selector來控制Button背景顏色
button.setBackground(ContextCompat.getDrawable(context,
R.drawable.button_input_selector));
button.setEnabled(true);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的android输入时背景颜色,Button根据EditText输入状态改变背景颜色的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 你的电脑性能过时了吗你的电脑性能过时了吗
- 下一篇: html session 登录页面跳转页