我有2个课程,Main和DialogOrder
主要
public class Main extends Fragment{
ImageView order;
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
order.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new DialogOrder(getActivity()).show();
}
});
return view;
}
public void init(Bundle savedInstanceState) {
order = (ImageView) view.findViewById(R.id.order);
order.setImageResource(R.drawable.orderd);
RelativeLayout.LayoutParams orderparams = new RelativeLayout.LayoutParams(Main.screenHeight / 8, Main.screenHeight / 8);
orderparams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
orderparams.addRule(RelativeLayout.CENTER_HORIZONTAL);
orderparams.setMargins(Main.screenHeight / 80, Main.screenHeight / 80, Main.screenHeight / 80, Main.screenHeight / 30);
order.setLayoutParams(orderparams);
}
public void update_UI(){
order.setVisibility(View.INVISIBLE);
}
}
DialogOrder
public class DialogOrder extends Dialog {
Button button;
Main main;
Activity context;
public DialogOrder(Activity context) {
super(context);
this.context = context;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.order_dialog);
main = new Main();
button = (Button)findviewbyid(R.id.bd);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
main.update_UI();
dismiss();
}
});
}}
我想要的是当用户按下对话框上的按钮时将订单图像设置为INVISIBLE 现在代码给了我 显示java.lang.NullPointerException
可能我尝试更新UI错误 那么有人可以告诉我从子类更新父UI类的正确方法是什么?
答案 0 :(得分:1)
您可以通过将主片段传递给Dialog构造函数来更新它,也可以使用Listener/Callback
在主片段和对话框之间进行通信。
最佳做法是使用侦听器/回调,因为对话不应可以访问调用者。这也是与主片段分离的对话框。
首先,通过对话框中的界面创建侦听器:
public class DialogOrder extends Dialog {
...
Activity context;
private DialogListener listener;
public interface DialogListener {
void onButtonClicked();
}
public DialogOrder(Activity context, DialogListener listener) {
super(context);
this.context = context;
this.listener = listener;
}
...
}
然后,当按钮单击调用侦听器时:
public class DialogOrder extends Dialog {
Activity context;
private DialogListener listener;
public interface DialogListener {
void onButtonClicked();
}
public DialogOrder(Activity context, DialogListener listener) {
super(context);
this.context = context;
this.listener = listener;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
...
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listener.onButtonClicked();
dismiss();
}
});
}
}
现在,您可以使用侦听器创建对话框。像这样:
DialogOrder.DialogListener listener = new DialogOrder.DialogListener() {
@Ovveride
public void onButtonClicked() {
update_UI();
}
};
DialogOrder dialogOrder = new DialogOrder(getActivity(), listener);
dialogOder.show();
主要片段将在对话框中点击按钮。