Pankaj Bhardwaj Pankaj Bhardwaj - 6 months ago 20
Android Question

Not able to update TextView's text in custom dialog box

Please help. I have tried everything but failed every time. I am building an android app where I need to update text of a TextView in dialog box programmatically.
This dialog box is created using custom layout. Posting code below, Please help in updating value of tv1 to "It's new text". In XML layout file text was set to "old text".
After I run this program, value of tv1 in 'dialogabt', is still seen as "old text".

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button b1 = (Button) findViewById(R.id.b1);

//generating first dialog box
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Dialog dialog1 = new Dialog(MainActivity.this);
dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog1.setContentView(R.layout.setings);
dialog1.show();
}
});
}

//function to generate second dialogbox and update textview's text in it
public void abtit(View view) {
Dialog dialogabt = new Dialog(this);
dialogabt.requestWindowFeature(Window.FEATURE_NO_TITLE);

LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.custom2, null);
TextView tv1 = (TextView) dialogView.findViewById(R.id.firstapp);

System.out.println("Going to set new value");
tv1.setText("Its new text");
System.out.println("done setting new value");

dialogabt.setContentView(R.layout.custom2);
dialogabt.show();
}
}


setings.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/set3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="About app"
android:onClick="abtit"
/>
</RelativeLayout>


custom2.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="315dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/custom_alert2"
android:orientation="vertical" >
<TextView
android:id="@+id/firstapp"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:onClick="openapp2"
android:text="old text"
/>
</RelativeLayout>

Answer

Try this:

LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.custom2, null);

dialogabt.setContentView(R.layout.custom2);

TextView tv1 = (TextView) dialogabt.findViewById(R.id.firstapp);

System.out.println("Going to set new value");
tv1.setText("Its new text");
System.out.println("done setting new value");

dialogabt.show();