[英]Clear focus EditText when back button is pressed when softkeyboard is showing
我知道這里有很多關於這個問題的問題。 但他們中沒有人能得到我正在尋找的答案。
我在ScrollView中有7個ET。 當我啟動應用程序時,沒有ET有焦點,因為我在我的整體布局中添加了以下兩行:
android:focusable="true"
android:focusableInTouchMode="true"
當我點擊ET時,會顯示我想要的軟鍵盤,然后我設置了值(比方說20)。 我按下'2'后跟'0'然后按后退按鈕。 此時鍵盤消失,但焦點仍然存在。 當按下后退按鈕隱藏鍵盤時,我也希望清除焦點。
因為當清除焦點時,ET的布局設置為我想要的。
他們都有一些代碼,這是:
// Right Cable
RightCable = (EditText) findViewById (R.id.RightCable);
RightCable.setRawInputType(Configuration.KEYBOARD_12KEY);
RightCable.setOnFocusChangeListener(FocusChanged);
RightCable.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if(RightCable.isFocused()){
LengthRightCable = Double.parseDouble(RightCable.getText().toString());
Calculate();
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().matches("")) {
RightCable.setText("0.00");
Selection.setSelection(RightCable.getText(), 0, 4);
}
}
});
我使用焦點監聽器將ET的輸入更改為5.00而不是0的數字。
OnFocusChangeListener FocusChanged = new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
EditText et = (EditText) v;
et.setSelection(0, et.getText().length());
if(!hasFocus){
String userInput = et.getText().toString();
int dotPos = -1;
for (int i = 0; i < userInput.length(); i++) {
char c = userInput.charAt(i);
if (c == '.') {
dotPos = i;
}
}
if (dotPos == -1){
et.setText(userInput + ".00");
} else if(userInput.length() < 5) {
if ( userInput.length() - dotPos == 1 ) {
et.setText(userInput + "00");
} else if ( userInput.length() - dotPos == 2 ) {
et.setText(userInput + "0");
}
}
}
}
};
為此,您必須在布局文件的父布局上使用onTouchListener。 在TouchListener上,您必須編碼以在EditText外部單擊時隱藏鍵盤。 請按照以下XML布局和Java類來解決此問題。
請按照以下網址解決此問題http://amitthaperandroidquery.blogspot.com/2011/10/remove-keyboard-after-click-outside.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.