請幫忙。我嘗試了一切,但每次都失敗了。我正在構建一個android應用程序,我需要以編程方式在對話框中更新TextView的文本。 該對話框是使用自定義佈局創建的。在下面發佈代碼,請幫助將tv1的值更新爲「It's new text」。在XML佈局文件中,文本被設置爲「舊文本」。 運行此程序後,'dialogabt'中tv1的值仍被視爲「舊文本」。無法更新自定義對話框中的TextView文本
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>
我發現你的代碼唯一的問題是,你是不是調用創建方法第二個對話框。因此對話框沒有被製作。 – Aradhna
第二個對話框由函數abtit()創建。它在setings.xml佈局的onclick屬性中提到。 –