【问题标题】:Requesting focus and displaying the keyboard in a view that has been added programmatically to a Dialog在以编程方式添加到对话框的视图中请求焦点并显示键盘
【发布时间】:2014-11-16 11:45:10
【问题描述】:

我想做的事:我有一个正在创建 AlertDialog 的活动,该活动以编程方式向 AlertDialog 引入和编辑文本。我想确保这样的编辑文本被聚焦并且键盘出现。

SO 中有很多线程,当视图使用布局创建时(因此,您拥有和 id),如何执行该操作(如 Android TextField : set focus + soft input programmatically)的良好解释出现了。

但是,有几条规则,特别是,您不能聚焦视图,直到它已经被布局在屏幕上。

所以发生在我身上的是,我以编程方式创建编辑文本,然后显示对话框,之后我无法访问我的视图,因为它没有 ID(无法使用 findviewbyid)。

那么,如何在 AlertDialog 中以编程方式创建的 Edittext 上请求焦点并显示键盘?

我在这里展示了一段代码(为简单起见,删除了积极按钮和消极按钮):

 final EditText input = new EditText(getApplicationContext());
     input.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,                     LayoutParams.WRAP_CONTENT));
     input.setGravity(Gravity.LEFT);
     input.setImeOptions(EditorInfo.IME_ACTION_DONE);
     input.setText(current_name);
     input.setTextColor(Color.BLACK);
     input.setBackgroundColor(Color.WHITE);
     input.setFocusableInTouchMode(true);
     input.requestFocus();



    AlertDialog EditDialog =new AlertDialog.Builder(this)
    //set message, title, and icon
    .setTitle(title_id) 
    .setIcon(R.drawable.ic_launcher_blue2)
    .setView(input)

我想做的是,当我的 EditDialog 在屏幕上布置时,我可以请求输入焦点并显示键盘。

【问题讨论】:

    标签: android keyboard


    【解决方案1】:

    试试这个:

    input.setFocusableInTouchMode(true);
    input.requestFocus();
    

    【讨论】:

    • 那不行,我已经试过了。您只能在已绘制的视图上请求焦点。这是创建步骤,当我执行 EditDialog.show(); 时会创建视图;
    猜你喜欢
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多