我可以动态修改Dialog的布局吗?

时间:2013-12-04 13:10:44

标签: java android android-layout dialog

我试图在这段代码中摆脱NPE:

Dialog  mutuallyDialog = new Dialog(getActivity());
mutuallyDialog.requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);

RelativeLayout container = (RelativeLayout) getActivity().findViewById(R.layout.new_couple);
container.findViewById(R.id.popup_av2).setBackground(someDrawable); // NPE, drawable returned form elsewhere

mutuallyDialog.setContentView(container);
mutuallyDialog.show();

R.layout.new_couple只是一个简单的布局xml,包含一些文本和ImageViews popup_av1和popup_av2。

我想要实现的是能够在显示对话框之前更改这两个ImageViews src但由于某些原因上面的代码无效。这种方法是否正确?

1 个答案:

答案 0 :(得分:1)

您不会通过ID调用查找视图,例如:

RelativeLayout container = (RelativeLayout)getActivity().findViewById(R.layout.new_couple);

相反,您可以将其设置为内容视图,如:

mutuallyDialog.setContentView(R.layout.new_couple);

现在,您可以在mutualDialog上按ID查找查找视图,以查找布局中的视图并更改它们:

mutuallyDialog.findViewById(R.id.popup_av2).setBackground(someDrawable);

将您的代码更改为以下内容:

Dialog  mutuallyDialog = new Dialog(getActivity());
mutuallyDialog.requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
mutuallyDialog.setContentView(R.layout.new_couple);
mutuallyDialog.findViewById(R.id.popup_av2).setBackground(someDrawable); 


mutuallyDialog.show();

如果有帮助请告诉我