2012-02-05 84 views
0

更新的Android Activity的UI我有一個Activity其佈局是包含TextView id爲my_view,並與ID open_alert一個Button文件main.xml英寸點擊按鈕將打開一個AlertDialog,點擊確定即可解散。一旦AlertDialog被取消,我需要更新活動中TextView的值。如何從警告對話框

我無法從活動更新TextView的值。

+0

提供更多詳細信息 - 錯誤日誌?代碼失敗了嗎? – BitBank 2012-02-05 15:13:06

+0

提供您已經嘗試過的代碼... – 2012-02-05 15:15:51

回答

1

一種方法是重新啓動在OnClickListener的活動在您的快訊。如果你想傳遞一個值到視圖中,只需在intent中添加一個額外的屬性,並重置TextView中的值。我已經發布了一個粗略的代碼以供參考。

alert.setNeutralButton("OK", new OnClickListener() { 

     public void onClick(DialogInterface dialog, int which) { 
      //create a new intent 
      Intent intent = new Intent("YOUR ACTIVITY NAME"); 
      //add your value in the intent 
      int value = //your value 
      intent.putExtra("value",value); 
          //start your activity 
      startActivity(intent); 
     } 
    }); 

,並在您的活動

Intent intent = getIntent(); 
yourTextView.setText(intent.getExtras().getString("value")); 

不知道這是否是最有效的方式做到這一點,但應該工作。

+0

它會工作,但我們需要再次完成活動並重新啓動它,這不是那個gud的想法。而不是像下面這樣點擊按鈕時更新UI:
按鈕b =(按鈕)findviewbyId(R.id.b1); – 2012-02-05 16:46:40

3

只實現onClick偵聽肯定按鈕:

new AlertDialog.Builder(this) 
    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int whichButton) 
    { 
     TextView text = (TextView) v.findViewById(R.id.my_view); 
     if (text != null) 
     { 
     text.setText("new text"); 
     } 
    }) 
    .setNegativeButton(R.string.cancel, null).create().show(); 
0

首先,您應該確保android:editable屬性存在於XML文件中,並對目標TextView設置爲true。然後,在onClick()方法中,您只需要使用setText()。