设置单击侦听器时对话框崩溃



>i 创建一个自定义对话框类 此对话框运行良好并显示,但当 setOnClickListener 应用程序崩溃时。我认为问题出在setView中,请指导.我在片段中调用这个类/有什么问题

clDialogs = new Cl_Dialogs();
clDialogs.showPopup(getContext());

package ir.lilola.org;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Cl_Dialogs {
Dialog dialog;
public void showPopup(Context context){
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
Button Category = dialog.findViewById(R.id.category);
final Button Date = dialog.findViewById(R.id.date);
Button Time = dialog.findViewById(R.id.time);
Button Confirm = dialog.findViewById(R.id.confirm);
Confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
Button Delete = dialog.findViewById(R.id.del);
EditText Price = dialog.findViewById(R.id.price);
EditText Label = dialog.findViewById(R.id.label);
TextView dateText = dialog.findViewById(R.id.dateText);
TextView timeText = dialog.findViewById(R.id.timeText);
TextView labelText = dialog.findViewById(R.id.labelText);
TextView priceText = dialog.findViewById(R.id.priceText);
dialog.setContentView(R.layout.dialog_registers);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
}

你需要调用

dialog.setContentView(...);

早于任何

dialog.findViewById(...);

这是因为如果没有设置 contentView,findViewById(..)将返回null,因为它无法按给定 id 找到视图。

因此,当您尝试调用setOnClickListener(..)时,您正在针对null调用该方法,最终会得到NullPointerException

看看官方文件:这里

最新更新