android alertdialog 软键盘,android – 使用AlertDialog.Builder显示软键盘(数字)

博客讨论了在Android AlertDialog中如何自动显示数字键盘,而不需先点击EditText。作者遇到的问题是输入框需要被点击后键盘才会弹出,而目标是加载对话框时即显示数字键盘。尝试了设置软键盘状态始终可见,但这导致了标准键盘而非数字键盘出现。最终解决方案是结合使用`setSoftInputMode`和请求焦点,确保在Dialog打开时数字键盘随之出现,并在关闭Dialog时隐藏键盘。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我在AlertDialog中有一个EditText,但是当它弹出时,我必须在键盘弹出之前单击文本框.此EditText在XML布局中声明为“number”,因此当单击EditText时,会弹出一个数字小键盘.我想消除这个额外的点击,并在加载AlertDialog时弹出数字小键盘.

我发现的所有其他解决方案都涉及使用

dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

这不是一个可接受的解决方案,因为这会导致标准键盘而不是数字键盘弹出.有没有人有办法在AlertDialog中弹出数字键盘,最好是保持我的布局在XML中定义?

AlertDialog dialog = new AlertDialog.Builder(this)

.setTitle("Mark Runs")

.setView(markRunsView)

.setPositiveButton("OK", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

EditText runs = (EditText)markRunsView.findViewById(R.id.runs_marked);

int numRuns = Integer.parseInt(runs.getText().toString());

// ...

})

.setNegativeButton("Cancel", null)

.show();

编辑:我想非常清楚我的布局已经有了:

android:inputType="number"

android:numeric="integer"

我也试过这个:

//...

.setNegativeButton("Cancel", null)

.create();

EditText runs = (EditText)markRunsView.findViewById(R.id.runs_marked);

runs.setInputType(InputType.TYPE_CLASS_NUMBER);

dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

dialog.show();

但那也行不通.使用setSoftInputMode行,我可以在AlertDialog加载时获得完整的键盘;没有它,我仍然一无所获.在任何一种情况下,点击文本框都会弹出数字键盘.

再次编辑:

这是EditText的XML

android:id="@+id/runs_marked"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginLeft="4dip"

android:inputType="number"

android:numeric="integer">

解决方法:

来得有点晚了,但今天我遇到了同样的问题.这就是我解决它的方式:

对话框打开时调用键盘就像你一样:

dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

现在,进入Dialog我假设你有一个只接受数字的EditText字段.只需要关注该字段,标准键盘就会自动转换为数字键盘:

final EditText valueView = (EditText) dialogView.findViewById(R.id.editText);

valueView.requestFocus();

现在,您必须记住在完成Dialog后关闭键盘.只需将其放入正/负/中性按钮单击监听器:

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

imm.hideSoftInputFromWindow(valueView.getWindowToken(), 0);

标签:android-keypad,android,alertdialog

来源: https://codeday.me/bug/20190826/1733418.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值