Android 軟鍵盤遮擋Dialog
阿新 • • 發佈:2019-01-09
工作中發現在AlertDialog中加入EditText後,Android 4.4 ,SDK19 或以下的手機,軟鍵盤彈出後會遮擋Dialog中的按鈕,而5.1的手機Dialog會自動向上移動一些。
首先遇到不會的先上網查查吧
網上有一些方案,
Window window = dialog.getWindow(); if (window != null) { window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); }
跑了一下,沒效果,也許是沒用對地方吧,還有一些別的方案,試了試都沒效果,自己想辦法吧
經過一番研究,發現直接在構造Dialog時加上Theme,在Theme裡設定軟鍵盤彈出方案 就可以了
第一步:建立theme:
在styles.xml檔案寫
<style name="dialog_soft_input" parent="Theme.AppCompat.Light.Dialog.Alert"> <item name="android:windowSoftInputMode">stateVisible|adjustPan</item> </style>
第二步:寫一個需要的EditText layout檔案 edittext.xml
<?xml version="1.0" encoding="utf-8"?> <EditText xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/frame_gray" android:gravity="top" android:maxLength="500" android:padding="8dp" android:textSize="13sp" />
第三步:用style構造AlertDialog,然後把自己的EditText加進去,加自己的操作然後show就好了
final EditText editText = (EditText) LayoutInflater.from(this).inflate(R.layout.edittext, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.dialog_soft_input).setView(editText); builder.setTitle("標題") .setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) {
// do something } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show();
全部程式碼: http://download.csdn.net/download/suihs11/10041710
https://github.com/suihs11/SoftInputAlertDialog