在dismissDialog之后将焦点设置为EditText

时间:2013-07-19 13:04:05

标签: android

我需要修复一些已弃用的代码。 在对话框(showdialog)被解雇之后,我想要一个edittext来聚焦,选择文本和键盘。这段代码不会发生这种情况。

使用此代码,没有焦点,但文本被选中。

...
alert.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    EditText txtE = (EditText) findViewById(R.id.ORE);
                    dismissDialog(DIALOG_NO_E);
                    txtE.selectAll();
                    txtE.requestFocus();                        
                }
            });
...

连连呢?

1 个答案:

答案 0 :(得分:1)

在requestfocus之后添加它会使它工作。但感觉不对。

txtE.postDelayed(new Runnable() {
                        public void run() {
                            android.view.inputmethod.InputMethodManager keyboard = (android.view.inputmethod.InputMethodManager) getSystemService(android.content.Context.INPUT_METHOD_SERVICE);
                            keyboard.showSoftInput(txtE, 0);
                        }
                    }, 200);

最终结果

...
alert.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    dismissDialog(DIALOG_NO_E);
                    txtE.selectAll();
                    txtE.requestFocus();                        
                }
            });
txtE.postDelayed(new Runnable() {
                            public void run() {
                                android.view.inputmethod.InputMethodManager keyboard = (android.view.inputmethod.InputMethodManager) getSystemService(android.content.Context.INPUT_METHOD_SERVICE);
                                keyboard.showSoftInput(txtE, 0);
                            }
                        }, 200);
...

如果某人有更好的解决方案或答案为什么我必须这样做,我会在星期一给你最新的答案。

为此,我必须创建txtE作为在构造函数中初始化的静态变量。在我的灵魂中,这并没有让我感觉良好。所以,如果有人有更好的想法,那就告诉你。