这是片段的Java文件代码:

@SuppressLint({"NewApi", "ResourceAsColor"})
public void createCardView(String id, String date, final String order) {
    flag = true;
    cardView = new CardView(context);
    cardView.setLayoutParams(layoutParamsCard);
    cardView.setElevation(5);
    relativeLayout = new RelativeLayout(context);
    relativeLayout.setLayoutParams(layoutParamsRelative);
    textView = new TextView(context);
    orderID = new TextView(context);
    textView.setLayoutParams(layoutParamsTextView);
    textView.setText("Order ID:");
    textView.setTextColor(Color.parseColor("#1e1e1e"));
    textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
    orderID.setLayoutParams(layoutParamsTextViewID);
    orderID.setText(id);
    orderID.setTextColor(Color.parseColor("#646464"));
    orderID.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
    orderDate = new TextView(context);
    orderDate.setText(date);
    orderDate.setLayoutParams(layoutParamsOrderDate);
    viewOrder = new Button(context);
    viewOrder.setText("View Order");
    viewOrder.setTextColor(Color.parseColor("#ffffff"));
    viewOrder.setBackgroundColor(Color.parseColor("#326432"));
    viewOrder.setLayoutParams(layoutParamsViewOrder);
    viewOrder.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LayoutInflater inflater = getLayoutInflater();
            final View dialogView = inflater.inflate(R.layout.view_order_dialog,null);
            dialogBuilder.setView(dialogView);
            final TextView orderTextView = dialogView.findViewById(R.id.orderTextView);
            final Button close = dialogView.findViewById(R.id.close);
            orderTextView.setText(order);
            dialogBuilder.setTitle("Order ID: " + orderID.getText().toString());
            final AlertDialog alertDialog = dialogBuilder.create();
            alertDialog.show();
        }
    });
    cardView.addView(relativeLayout);
    relativeLayout.addView(textView);
    relativeLayout.addView(orderID);
    relativeLayout.addView(viewOrder);
    relativeLayout.addView(orderDate);
    gridLayout.addView(cardView);
}


我无法从片段启动自定义dialogview。当我打开该片段时,它会使应用程序崩溃。我正在使用此代码动态创建卡并为每张卡创建OnClickListner。

最佳答案

您的活动context在此行中为null:

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()); // getActivity() is getting null here


为了避免崩溃,您应该包装代码并检查活动上下文是否不为null,如下所示:

if(getActivity() != null){
   AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
   LayoutInflater inflater = getLayoutInflater();
   final View dialogView = inflater.inflate(R.layout.view_order_dialog,null);
   dialogBuilder.setView(dialogView);
   final TextView orderTextView = dialogView.findViewById(R.id.orderTextView);
   orderTextView.setText(order);
   final AlertDialog alertDialog = dialogBuilder.create();
   alertDialog.show();
}

09-30 14:32
查看更多