我创建了一个自定义对话框类,该对话框运行良好并显示出来,但是当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();
}
}
答案 0 :(得分:1)
您需要致电
dialog.setContentView(...);
早于任何
dialog.findViewById(...);
这是因为没有设置contentView,findViewById(..)
将返回null
,因为它无法通过给定的ID查找视图。
因此,当您尝试调用setOnClickListener(..)
时,您正在针对null
调用方法,最终得到NullPointerException
看看官方文档:Here