gpt4 book ai didi

java - 调用 Setter 方法时自定义对话框 fragment 崩溃

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:03:35 24 4
gpt4 key购买 nike

我有一个像这样的 CustomDialogFragment

public class CustomDialogFragment extends DialogFragment {

private LinearLayout containerView;


public static CustomDialogFragment newInstance() {
CustomDialogFragment fragment = new EDActionSheet();
return fragment;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

final Dialog dialog = new Dialog(getActivity());
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

//MARK - containerView
LinearLayout.LayoutParams containerViewLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

containerView = new LinearLayout(dialog.getContext());
containerView.setLayoutParams(containerViewLayoutParams);
containerView.setOrientation(LinearLayout.VERTICAL);
dialog.setContentView(containerView);
DisplayMetrics displaymetrics = new DisplayMetrics();
dialog.getWindow().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
params.width = (int) (displaymetrics.widthPixels * 0.95);
params.gravity = Gravity.BOTTOM;
dialog.getWindow().setAttributes(params);

return dialog;
}

public void setColor(int color) {
containerView.setBackgroundColor(color);
}

从外部调用 DialogFragment。

    CustomDialogFragment fragment = CustomDialogFragment.newInstance();
fragment.setColor(ContextCompat.getColor(this, Color.BLUE));
fragment.show(getFragmentManager(), "Dialog");

我收到崩溃消息

 testapp.android.testapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: id.testapp.android.testapp, PID: 5749
java.lang.NullPointerException: Attempt to invoke virtual method 'void
id.testapp.android.testapp.controls.CustomDialogFragment.setColor(int)'
on a null object reference
at
id.testapp.android.testapp.controls.CustomDialogFragment.setColor(CustomDialogFragment.java:234)

有什么想法吗?

最佳答案

您的 containerView 引用尚未初始化。看看 onCreateDialog() 在初始化之前是如何被调用的。

您需要通过以下几种方式之一进行重构。最简单的方法可能只是让 setColor 方法只存储一个变量,说明“containerView”在初始化时也应该设置它的背景。

关于java - 调用 Setter 方法时自定义对话框 fragment 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34553498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com