我有一个文本,我在其中激活触摸事件。现在我希望如果我的文本为空或为空或显示提示,则必须取消激活Touch事件。
text1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(text1.equals("")){
}
else{
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
text1.setBackgroundColor(Color.RED);
InputConnection ic = getCurrentInputConnection();
ic.commitText(textOne, 1);
break;
case MotionEvent.ACTION_UP:
text1.setBackgroundColor(Color.YELLOW);
break;
}
}
return true;
}
}
但是当我按照上述指定的条件触摸我的文字时,它会使屏幕崩溃以及仍然激活Touch。有什么建议吗?
答案 0 :(得分:1)
我认为您的应用崩溃了,因为如果text1为null,则在尝试此操作时会出现空指针异常:if(text1.equals(""))
所以你应该尝试一下:
text1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(text1!=null && !text1.trim().equals("")){
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
text1.setBackgroundColor(Color.RED);
InputConnection ic = getCurrentInputConnection();
ic.commitText(textOne, 1);
break;
case MotionEvent.ACTION_UP:
text1.setBackgroundColor(Color.YELLOW);
break;
}
}
return true;
}
}
答案 1 :(得分:0)
最后我找到了答案。解决方案是:
if(text1.getText()!=null && !text1.getText().equals("")){
text1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
text1.setBackgroundColor(Color.RED);
InputConnection ic = getCurrentInputConnection();
ic.commitText(textOne, 1);
break;
case MotionEvent.ACTION_UP:
text1.setBackgroundColor(Color.YELLOW);
break;
}
return true;
}
}
); }