记录下EditText的几个设置

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

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

布局文件(部分):

  

    

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);

你可能感兴趣的:(Android)