不推荐您描述的设计。您违反了focusable
属性的目的,即不控制用户是否可以更改EditText
组件中的文本。
如果您计划提供替代输入法,因为用例似乎需要这样做(例如,您只允许可编辑文本字段中的特定符号集),那么您可能应该在不允许用户的时间内完全禁用文本编辑更改字段的值。
声明您的可编辑字段:
<EditText
android:id="@+id/edit_text_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" />
请注意,它的focusable
属性保留了默认值。没关系,我们稍后会处理。声明一个将开始编辑过程的按钮:
<Button
android:id="@+id/button_show_ime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start editing" />
现在,在您的Activity
声明中:
private EditText editText2;
private KeyListener originalKeyListener;
private Button buttonShowIme;
并onCreate()
这样做:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ime_activity);
// Find out our editable field.
editText2 = (EditText)findViewById(R.id.edit_text_2);
// Save its key listener which makes it editable.
originalKeyListener = editText2.getKeyListener();
// Set it to null - this will make the field non-editable
editText2.setKeyListener(null);
// Find the button which will start editing process.
buttonShowIme = (Button)findViewById(R.id.button_show_ime);
// Attach an on-click listener.
buttonShowIme.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Restore key listener - this will make the field editable again.
editText2.setKeyListener(originalKeyListener);
// Focus the field.
editText2.requestFocus();
// Show soft keyboard for the user to enter the value.
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText2, InputMethodManager.SHOW_IMPLICIT);
}
});
// We also want to disable editing when the user exits the field.
// This will make the button the only non-programmatic way of editing it.
editText2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// If it loses focus...
if (!hasFocus) {
// Hide soft keyboard.
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText2.getWindowToken(), 0);
// Make it non-editable again.
editText2.setKeyListener(null);
}
}
});
}
我希望带有所有注释的代码是不言自明的。在 API 8 和 17 上测试。