2012-12-17 79 views
1

我的作品基本上在我的修改後的示例下面我有2個編輯框我希望兩個值都顯示在警告框中,其餘代碼工作正常,警報框確實顯示,但沒有輸入的值。如何顯示用戶在Android對話框中輸入EditText值

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(); 
     } 
    }); 

回答

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(); 
     } 
    }); 
} 
+0

@ user1910290:同時聲明'字符串usernm'和'字符串passnm'在類級別意味着'onCreate'之前,那麼你將能夠在整個班級訪問這些變量 –

+0

謝謝...代碼運行,但值顯示爲空 – user1910290

+0

@ user1910290:請參閱我的編輯答案 –

相關問題