2013-05-22 80 views

回答

2

蔭,你可以嘗試

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 
    } 

問候

+0

這種解決方案意味着我將無法使用AlertDialog.Builder類? – mjn

+0

ofc,我做了編輯;) – Oli

+0

這很容易:)謝謝 – mjn

2

如果你正在使用你的對話框的自定義XML的佈局,你可以使用<requestFocus />你的EditText

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

    <requestFocus /> 
</EditText> 

或者,如果你想這樣做編程,上所示的對話框EditText後您的使用.requestFocus()。假設你有一個包含用戶名和密碼字段命名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(); 
相關問題