1

我修改后的工作示例基本上在下面我有 2 个编辑框我希望两者的值都显示在警报框中,其余代码工作正常,警报框确实显示但没有输入的值。

public class Main extends Activity {

    EditText username = null;
    EditText password = null;
    Button login;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        EditText usern = (EditText) findViewById(R.id.username);
        EditText pass = (EditText) findViewById(R.id.password);
        Button login = (Button) findViewById(R.id.login);
        String usernm = usern.getText().toString();
        String passnm = pass.getText().toString();
        final Builder alert = new AlertDialog.Builder(this)
            .setTitle("SHOW FIELDS")
            .setMessage("USERNAME:" + usernm + "  PASSWORD:" + passnm)
            .setNegativeButton("CLOSE", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) { 
                    // do nothing
                    closeContextMenu();
                }
             });
         login.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 alert.show();
             }
         });
4

1 回答 1

1

您将需要在按钮上获取 EditText 的值,因此在 AlertDialog 中显示为:

login.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
          usernm = usern.getText().toString();
          passnm = pass.getText().toString();
             alert.show();
         }

usernmpassnm在类级别声明

编辑: 或者最好的方法是创建一个显示警报的方法并在按钮点击时调用它:

  public void showalert(){
          usernm = usern.getText().toString();
          passnm = pass.getText().toString();
          alert = new AlertDialog.Builder(Main.this)
            .setTitle("SHOW FIELDS")
            .setMessage("USERNAME:" + usernm + "  PASSWORD:" + passnm)
            .setNegativeButton("CLOSE", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) { 
                    // do nothing
                    closeContextMenu();
                }
             });
     alert.show();
    }

并在按钮单击时调用此方法:

 login.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        showalert();
     }:
 });

并在类级别声明所有变量,您可以通过这些变量在整个类中访问它:

public class Main extends Activity {
EditText usern ;
EditText pass ;
Button login;

String usernm ,passnm; //<<< Declare here
Builder alert;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
     usern = (EditText) findViewById(R.id.username);
     pass = (EditText) findViewById(R.id.password);
     login = (Button) findViewById(R.id.login);

         login.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
              showalert();
         }
     });
 }
于 2012-12-17T15:16:27.207 回答