记录下EditText的几个设置

背景:EditText的几个用法,经常找来找去。因此把项目里的一段代码摘来做为例子。在一个布局内定义了一个EditText和一个Button。实现如下功能:

  1. EditText默认不可编辑。
  2. 点击Button,EditText进去可编辑状态,自动获得焦点,并且唤起键盘。
  3. 再次点击Button,EditText恢复不可编辑状态,并且隐藏键盘。

布局文件(部分):

  <EditText
    android:id="@+id/et_photo_desc"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:padding="5dp"
    android:textColor="@color/font_color_level_3"
    android:background="@drawable/default_input_edit"
    android:enabled="false"
    android:gravity="center_vertical"
    android:inputType="textMultiLine"
    android:hint="@string/hint_click_to_add_desc"
    android:textSize="@dimen/content_font_size_level_2" />

    <Button
      android:id="@+id/btn_edit_desc"
      android:layout_width="wrap_content"
      android:layout_height="50dp"
      android:layout_centerInParent="true"
      android:textColor="@color/font_color_level_2"
      android:text="@string/photo_view_edit_edit_desc"
      android:onClick="onEditDescButtonClicked" />

Button的OnClick方法实现:

    public void onEditDescButtonClicked(View view) {
        Button btnEdit = (Button) view;

        etPhotoDesc.setEnabled(!etPhotoDesc.isEnabled());

        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (etPhotoDesc.isEnabled()) {
            etPhotoDesc.requestFocus();
            inputManager.showSoftInput(etPhotoDesc, InputMethodManager.SHOW_FORCED);
        } else {
            SpotFile spotFile = spotInfo.getFiles().get(currentIndex);
            spotFile.setDescription(etPhotoDesc.getText().toString());
            inputManager.hideSoftInputFromWindow(etPhotoDesc.getWindowToken(), 0);
        }

        int titleId = etPhotoDesc.isEnabled() ? R.string.photo_view_edit_save_desc : R.string.photo_view_edit_edit_desc;
        btnEdit.setText(titleId);
    }

知识点:

1. 内容多行显示

android:inputType="textMultiLine"

2. 内容垂直居中

android:gravity="center_vertical"

3. 唤起输入法

inputManager.showSoftInput(etPhotoDesc, InputMethodManager.SHOW_FORCED);

4. 隐藏输入法

inputManager.hideSoftInputFromWindow(etPhotoDesc.getWindowToken(), 0);

你可能感兴趣的:(EditText键盘)