软键盘的显示与隐藏
程序员文章站
2022-04-20 08:28:44
...
参考:
Android : 隐藏软键盘
Android手动显示和隐藏软键盘方法总结
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="软键盘开关"
android:textColor="@color/colorAccent"
android:textSize="16sp" />
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开启软键盘"
android:textColor="@color/colorAccent"
android:textSize="16sp" />
<Button
android:id="@+id/btn3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="关闭软键盘"
android:textColor="@color/colorAccent"
android:textSize="16sp" />
<EditText
android:id="@+id/et1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:imeOptions="actionNext"
android:inputType="number|numberDecimal"
android:maxLength="4"
android:selectAllOnFocus="true"
android:textColor="#333333"
android:textSize="15sp" />
</LinearLayout>
代码
/**
* 开关软键盘
*/
public class MainActivityII extends AppCompatActivity {
private EditText mEt1;
private Button mBtn1;
private Button mBtn2;
private Button mBtn3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainii);
mEt1 = (EditText) findViewById(R.id.et1);
mBtn1 = ((Button) findViewById(R.id.btn1));
mBtn2 = ((Button) findViewById(R.id.btn2));
mBtn3 = ((Button) findViewById(R.id.btn3));
mBtn1.setOnClickListener(new View.OnClickListener() {//切换
@Override
public void onClick(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
});
mBtn2.setOnClickListener(new View.OnClickListener() {//开
@Override
public void onClick(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
mEt1.requestFocus();
imm.showSoftInput(mEt1, 0);//可toggle关闭
// imm.showSoftInput(mEt1, InputMethodManager.SHOW_FORCED);
//强制开启只能mBtn3关,不能mBtn1的toggle关闭
}
}
});
mBtn3.setOnClickListener(new View.OnClickListener() {//关
@Override
public void onClick(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(mEt1.getWindowToken(), 0);
}
}
});
}
}
上一篇: PopupWindow与软件盘冲突,且软键盘出现背景色
下一篇: android 软键盘弹出与隐藏