我正在开发一个有两个EditTexts和两个ImageViews的应用程序(我的ImageView是一个删除图标EditText)
我希望当我将焦点设置在EditText1上时,会出现ImageView1并且ImageView2消失,当我将焦点设置在EditText2上时,会出现ImageView2并且ImageView1会消失。
我认为我应该使用TextWatcher()
方法而不是setOnKeyListener()
,但我不知道如何做。
我在onCreate()
方法中编写了这段代码,但我遇到了一个问题:当我将焦点设置在EditText1上时,我必须在其中写一些内容以使image_1出现并且image_2消失(反之亦然)我将重点放在EditText2)
editText1.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
image_1.setVisibility(View.VISIBLE);
image_2.setVisibility(View.INVISIBLE);
return false;
}
});
editText2.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
image_1.setVisibility(View.INVISIBLE);
image_2.setVisibility(View.VISIBLE);
return false;
}
});
答案 0 :(得分:0)
我认为你可以使用TextChangedListener:
editText1.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) {
}
@Override
public void afterTextChanged(Editable s) {
imageView1.setVisibility(View.VISIBLE);
imageView2.setVisibility(View.INVISIBLE);
}
});
editText2.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) {
}
@Override
public void afterTextChanged(Editable s) {
imageView1.setVisibility(View.INVISIBLE);
imageView2.setVisibility(View.VISIBLE);
}
});
我希望它可以帮到你。
答案 1 :(得分:0)
我认为OnKeyListener
或TextWatcher
不是您需求的正确解决方案。
您想要的是OnFocusChangeListener
:
View.OnFocusChangeListener focusChangeListener1 = new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
image_1.setVisibility(View.VISIBLE);
image_2.setVisibility(View.INVISIBLE);
}
}
editText1.setOnFocusChangeListener(focusChangeListener1);
View.OnFocusChangeListener focusChangeListener2 = new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
image_1.setVisibility(View.INVISIBLE);
image_2.setVisibility(View.VISIBLE);
}
}
editText2.setOnFocusChangeListener(focusChangeListener2);