我有一个显示用户定义的文本标签的EditText。它显示为带有白色字母的蓝色背景。
但当用户点击它时,我希望它变为带有黑色字母的白色背景,以表明它处于编辑模式。
然后,当这个人点击退出时,我希望它像以前一样变成蓝底白。此外,如果输入的文本比显示器宽,我希望它左对齐。
我该怎么做?
请尝试以下操作:
edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
v.setBackgroundColor(Color.WHITE);
((EditText) v).setTextColor(Color.BLACK);
} else {
v.setBackgroundColor(Color.BLUE);
((EditText) v).setTextColor(Color.WHITE);
}
}
});
有多种方法可以实现
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// do some operation on text of text1 field
// do some operation on text of text2 field
}
我不确定你能否在布局上做到这一点。尝试在布局中使用选择器。也许这可以奏效。对于文本颜色,请使用单独的选择器;对于编辑文本背景,请使用另一个选择器。选择器的格式如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="" /> <!-- pressed -->
<item android:state_focused="true"
android:color="" /> <!-- focused -->
<item android:color="" /> <!-- default -->
</selector>
在颜色属性中填充所需颜色。
您可以尝试使用以下中的textWatcher
EditText text=new EditText(this);
text.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
//change the color before editing
}
@Override
public void afterTextChanged(Editable s) {
//change the color after edited
}
});
我认为这可能对你有帮助。。