如何将焦点设置为AlertDialog中的特定输入字段?

时间:2013-05-22 13:10:11

标签: android alertdialog

在带有两个输入字段(用户名/密码)的登录对话框中,我想将焦点设置在第二个字段上(因为用户名存储在首选项中)。

AlertDialog.Builder是否提供了设置焦点的方法?

2 个答案:

答案 0 :(得分:3)

如果您在对话框中使用自定义XML布局,则可以在<requestFocus />上使用EditText

<EditText
    android:id="@+id/etPassword"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword" >

    <requestFocus />
</EditText>

或者如果您想以编程方式执行此操作,请在显示对话框后在.requestFocus()上使用EditText。假设您有一个名为custom_login_dialog.xml的自定义布局,其中包含用户名和密码字段:

    // Inflate your custom layout
    LayoutInflater inflater = (LayoutInflater) getLayoutInflater();
    View customView = inflater.inflate(R.layout.custom_login_dialog, null);

    // Define your EditText fields
    final EditText etUsername = (EditText) customView.findViewById(R.id.etUsername);
    final EditText etPassword = (EditText) customView.findViewById(R.id.etPassword);

    // Build the dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(customView); // Set the view of the dialog to your custom layout
    builder.setTitle("Login");
    builder.setPositiveButton("Login", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ...
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ...
        }
    });

    // Create and show the dialog
    builder.create().show();

    // Request focus after showing dialog
    etPassword.requestFocus();

答案 1 :(得分:2)

我也使用alertdialog,你可以尝试

final EditText input = new EditText(this);    
input.setInputType(InputType.TYPE_CLASS_TEXT); // you should use .TYPE_TEXT_VARIATION_PASSWORD
input.requestFocus();

示例:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(x);
        builder.setIcon(R.drawable.x);

        final EditText input = new EditText(this);

        input.setInputType(InputType.TYPE_CLASS_TEXT);
        input.setText("mytext");

        builder.setView(input);

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
            @Override
          // xy

        });
        builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() {
            @Override
            // xy
        });

        builder.show();

        input.requestFocus(); // <--- for the focus
    }

此致