我在Dialog
类中有以下代码:
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("MyTitle")
.setMessage("MyMessage")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/////////LINE OF MY QUESTION/////////////////////
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
,我需要在MainActivity
“确定”按钮(OnClickListener for
)内从另一个类(///LINE OF MY QUESTION///
)调用方法“ OK_Clicked”。我已经尝试过:
MainActivity xyz = new MainActivity();
xyz.OK_Clicked();
但是每次我单击“确定”按钮时,应用程序都会崩溃并说:“ MyApp已停止。”
答案 0 :(得分:0)
在需要的地方定义DialogInterface.OnClickListener
(例如,将其分配给类级变量),然后创建一个方法从类外部调用onClick
方法。
//Just take your existing anonymous subclass definitions and put them here
private DialogInterface.OnClickListener listener1 = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
};
private DialogInterface.OnClickListener listener2 = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("MyTitle")
.setMessage("MyMessage")
.setPositiveButton("OK", listener1)
.setNegativeButton("Cancel", listener2);
return builder.create();
}
// Call these methods from outside this class
public void onClick1(){
listener1.onClick();
}
public void onClick2(){
listener2.onClick();
}