3

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

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

4

2 回答 2

5

我也在使用 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
    }

问候

于 2013-05-22T13:12:30.867 回答
4

如果您为对话框使用自定义 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();
于 2013-05-22T13:16:19.460 回答