请帮忙。我已经尝试了一切,但每次都失败了。我正在构建一个Android应用程序,我需要以编程方式在对话框中更新TextView的文本。 此对话框使用自定义布局创建。发布以下代码,请帮助将tv1的值更新为"它的新文字"。在XML布局文件中,文本被设置为"旧文本"。 运行此程序后,“对话框”中的tv1值仍然被视为"旧文本"。
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>
答案 0 :(得分:0)
删除以下行,因为您在将文本设置为textView
后正在设置contentViewdialogabt.setContentView(R.layout.custom2);
并将此行添加到下面
View dialogView = inflater.inflate(R.layout.custom2, null);
答案 1 :(得分:0)
试试这个:
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();
答案 2 :(得分:0)
检查 abtit()方法,您在一个自定义视图中设置值,在警告对话框中设置另一个视图,因此它不会影响您为dialogView对象设置的值。
所以只需更改下面的行,
dialogabt.setContentView(R.layout.custom2);
通过
dialogabt.setView(dialogView);
它会起作用