我已经对此进行了搜索和搜索,但不幸的是,我没有找到任何有用的信息来说明如何在自定义对话框中重用以前膨胀的视图。
这是我尝试过的(没有一个有效)
方法一:
将我的 alertdialog 构建器保持为全局并在其中onCreate()
执行我需要的操作:
private AlertDialog.Builder dialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new AlertDialog.Builder(this);
detailView = getLayoutInflater().inflate(R.layout.detail, null);
TextView textview1 = (TextView)detailView.findViewById(R.id.lblName);
TextView textview2 = (TextView)detailView.findViewById(R.id.lblSubtitle);
textview1.setText("Test1");
textview2.setText("Test2");
dialog.setView(detailView);
dialog.create();
btnSearch = (ImageView)findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
}
然后在我需要的时候显示它:dialog.show();
没用,LogCat 输出:
Uncaught handler: thread main exiting due to uncaught exception
java.lang.IllegalStateException: The specified child already has a parent.
You must call removeView() on the child's parent first.
方法二:
onCreate()
只需膨胀布局并在点击事件中:
dialog = new AlertDialog.Builder(this);
TextView textview1 = (TextView)detailView.findViewById(R.id.lblName);
TextView textview2 = (TextView)detailView.findViewById(R.id.lblSubtitle);
textview1.setText("Test1");
textview2.setText("Test2");
dialog.setView(detailView);
dialog.create();
但是它崩溃了,给出了相同的错误输出。
当然我已经阅读了输出并试图找到父级,所以我猜父级将是对话框本身,但它没有任何删除视图的方法,所以我真的不知道该怎么做。
还有一种方法可以重用 textview 引用吗?
(我知道它的编码很糟糕,只是想让它工作,我会对其进行适当的重构。