在具有自定义视图的自定义对话框类中,我要处理活动或片段中按钮的单击,我创建了一个界面来处理按钮单击但显示错误。
尝试在空对象引用上调用接口方法'void com.ymcaspi.util.CustomDialog $ DialogInterface.doLogin(com.ymcaspi.util.CustomDialog)'
我的对话课是
public class CustomDialog extends Dialog implements
android.view.View.OnClickListener {
public Activity activity;
public Button btnYes, btnNo;
CustomDialog customDialog;
public CustomDialog(Activity activity) {
super(activity);
this.activity = activity;
}
DialogInterface dialogInterface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.alert_login);
btnYes = (Button) findViewById(R.id.btn_yes);
btnNo = (Button) findViewById(R.id.btn_no);
btnYes.setOnClickListener(this);
btnNo.setOnClickListener(this);
}
//in custom adapter class i want to handle click of button from Activity or fragment, I have created a interface for handling button click
//but showing
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_yes:
customDialog=new CustomDialog(activity);
dialogInterface.doLogin(customDialog);
break;
case R.id.btn_no:
dismiss();
break;
default:
break;
}
dismiss();
}
public interface DialogInterface{
void doLogin(CustomDialog dialog);
}
}
我已经在片段中实现了此接口,但无法正常工作吗?
答案 0 :(得分:2)
您没有在对话框上初始化 dialogInterface ,如果您在Activity上实现了接口,请将Activity设置为对话框界面
public CustomDialog(Activity activity,DialogInterface dialogInterface ) {
super(activity);
this.activity = activity;
this.dialogInterface = dialogInterface ;
}
答案 1 :(得分:0)
这里是一个示例,如果您打算从对话框中收到有关活动的回调,则可以尝试:
class YourActivity extends Activity implements DialogInterface {
void showDialog() {
CustomDialog dialog = // init your CustomDialog
dialog.setOnLoginClickListener(this);
dialog.show();
}
void doLogin() {
// Button yes has been clicked, do stuff...
}
}
并创建一个方法来在您的CustomDialog
类中分配侦听器:
public class CustomDialog extends Dialog implements OnClickListener {
private DialogInterface dialogInterface;
public void setOnLoginClickListener(DialogInterface dialogInterface) {
this.dialogInterface = dialogInterface;
}
}