防止 EditText 在旋转后聚焦

Jor*_*n H 5 keyboard android rotation android-edittext

我已经实现了一个简单的 EditText,它提供了一个完成按钮来隐藏键盘,并且在旋转到横向时它不会为 EditText 显示全屏对话框。但是有一个问题。当我点击完成关闭键盘然后我将设备旋转到横向时,键盘出现。如果我再次关闭它然后旋转到纵向键盘再次出现。

如何在旋转时保留键盘可见性状态 - 如果它在旋转前隐藏,则在旋转后不显示,但如果在旋转前可见,则在旋转后显示?

<EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1"
        android:inputType="text"
        android:imeOptions="flagNoFullscreen|actionDone" />
Run Code Online (Sandbox Code Playgroud)

我尝试在父容器(RelativeLayout)中设置android:descendantFocusability="beforeDescendants"android:focusableInTouchMode="true",但这并没有影响这种行为。

Pra*_*ena 2

有两个选项。在您的onCreate()方法中尝试这些选项

选项1。

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Run Code Online (Sandbox Code Playgroud)

选项2

edittext.clearFocus();
Run Code Online (Sandbox Code Playgroud)

此选项将焦点设置回活动中的第一个可聚焦视图。

编辑:

如果您的编辑文本本身是活动中的第一个可聚焦视图,则选项 2 将不起作用,因为clearFocus将焦点设置回活动中的第一个可聚焦视图。

选项 1 的使用:

public class MyActivity extends Activity {
EditText editText1;
boolean isKeyBoardOpen=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    editText1 = (EditText) findViewById(R.id.editText1);

    if(savedInstanceState!=null &&(savedInstanceState.getBoolean("isKeyBoardOpen",false)))
           this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    else  this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);


    final View activityRootView = findViewById(R.id.root_layout);
    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            Rect r = new Rect();
            //r will be populated with the coordinates of your view that area still visible.
            activityRootView.getWindowVisibleDisplayFrame(r);
            int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
            if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
                isKeyBoardOpen=true;
            }else isKeyBoardOpen=false;
        }
    });
 }


protected void onSaveInstanceState(final Bundle bundle) {
    super.onSaveInstanceState(bundle);
    bundle.putBoolean("isKeyBoardOpen",isKeyBoardOpen);

}
}
Run Code Online (Sandbox Code Playgroud)