簡體   English   中英

如何從警報對話框更新Android Activity的UI

[英]How to Update Android Activity's UI from Alert Dialog

我有一個Activity ,其布局是在文件main.xml包含TextView id為my_viewButton用id open_alert 單擊該按鈕將打開一個AlertDialog ,單擊OK即可將其關閉。 一旦AlertDialog被取消,我需要從活動中更新TextView的值。

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

只需為肯定按鈕實現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();

一種方法是在Alert中的OnClickListener上重新啟動活動。 如果要將值傳遞給視圖,只需在意圖中添加一個額外的屬性,然后在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"));

不知道這是否是最有效的方法,但是應該可行。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM