方向更改时键盘消失

时间:2016-11-08 00:37:32

标签: android android-fragments android-softkeyboard android-orientation

我有一个EditText片段,并使用事务将其添加到布局中。但如果我旋转到横向,软键盘就会消失。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (getSupportFragmentManager().findFragmentById(R.id.fragmentContainer) == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragmentContainer, new FragmentWithEditText())
                    .commit();
        }
    }
}

我希望在使用片段事务轮换后,键盘状态仍然保持不变。因为如果我不使用事务,但在布局中直接添加片段,键盘就不会消失。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <fragment
        android:tag="fragmentWithKeyboard"
        android:name="com.test.FragmentWithEditText"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

我已尝试使用android:windowSoftInputMode="stateUnchanged"android:configChanges="keyboardHidden|orientation",但没有帮助。

我也用这种行为编写了一个示例应用https://github.com/anton9088/FragmentAndKeyboard

类似问题:

Retain soft-input/IME state on Orientation change

Keyboard dismissed on rotation to landscape mode Android

3 个答案:

答案 0 :(得分:1)

尝试将EditText的属性freezesText值设置为true。

您还可以手动在onViewCreated回调中添加焦点

答案 1 :(得分:0)

更改清单中的以下行,我相信它会对您有所帮助

<activity
android:name=".YourActivityName"
android:configChanges="orientation|screenSize">
</activity>

所以替换你的

android:configChanges="keyboardHidden|orientation"android:configChanges="orientation|screenSize"

答案 2 :(得分:0)

问题

问题在于我们的视图应该将windowSoftInputMode设置为stateUnchanged,这意味着:

当活动浮出水面时,软键盘将保持在最后一个状态,无论是可见还是隐藏。

在活动中,只需添加以下内容即可更改AndroidManifest.xml

<activity
    ...
    android:windowSoftInputMode="stateUnchanged"/>

不幸的是,它不适用于片段。

DialogFragment解决方案

如果您的片段是DialogFragment,则可以在创建对话框后将以下代码添加到onCreateDialog方法中来获取它:

Window window = dialog.getWindow();
if (window != null) {
    window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED);
}