简体   繁体   中英

How to Update Android Activity's UI from Alert Dialog

I have an Activity whose layout is in the file main.xml that contains a TextView with the id my_view and a Button with the id open_alert . Clicking on the button will open an AlertDialog which is dismissed on clicking ok. Once the AlertDialog is cancelled i need to update the value of the TextView from the activity.

I am not able to update the value of TextView from the activity.

Just implement onClick listener for positive button:

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

One way is to restart the activity on the OnClickListener in your Alert. If you want to pass a value into the view, just add an extra attribute in the intent and reset the value in the TextView. I have posted a rough code for reference.

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

and in your activity

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

Don't know if this is the most efficient way to do it, but should work.

First, you should make sure that the android:editable attribute is present in the XML file and set to true for the target TextView. Then, in the onClick() method you will just need to use setText().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM