あなたが説明したデザインは推奨されません。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 でテスト済み。