Answer the question
In order to leave comments, you need to log in
Confused about contexts (Fragment, AlertDialog, callback interface)?
Code below, dialog does not call ((ResultListener) context).onSpinnerSelectResult(keys[selecteditemid]); , error java.lang.ClassCastException: ru........android.Activity_Main cannot be cast to ru.............android.Dialog_SpinnerSelect$ResultListener . Already broke my head how to please the program, help :)
public class Fragment_Layers extends Fragment implements Dialog_SpinnerSelect.ResultListener {
......
void openDialog() {
Dialog_SpinnerSelect dialog = new Dialog_SpinnerSelect(getActivity());
dialog.show();
}
@Override
public void onSpinnerSelectResult(Integer result) {
//todo
}
}
public class Dialog_SpinnerSelect {
private Context context;
public Dialog_SpinnerSelect(Context context) {
this.context = context;
builder = new AlertDialog.Builder(context);
}
public void show() {
......
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
((ResultListener) context).onSpinnerSelectResult(keys[selecteditemid]);
}
});
.......
dialog.show();
}
public interface ResultListener {
void onSpinnerSelectResult(Integer result);
}
}
Answer the question
In order to leave comments, you need to log in
You are not confused in contexts, you do not understand what parameters you pass to constructors. I advise you to study Java more carefully.
Replace
Dialog_SpinnerSelect dialog = new Dialog_SpinnerSelect(getActivity());
on theDialog_SpinnerSelect dialog = new Dialog_SpinnerSelect(this);
;private Context context;
public Dialog_SpinnerSelect(Context context) {
this.context = context;
builder = new AlertDialog.Builder(context);
}
on theprivate Fragment_Layers fragment;
public Dialog_SpinnerSelect(Fragment_Layers fragment) {
this.fragment = fragment;
builder = new AlertDialog.Builder(fragment.getActivity());
}
;public void onClick(DialogInterface dialog, int arg1) {
((ResultListener) context).onSpinnerSelectResult(keys[selecteditemid]);
}
on thepublic void onClick(DialogInterface dialog, int arg1) {
((ResultListener) fragment).onSpinnerSelectResult(keys[selecteditemid]);
}
context cannot become a ResultListener. Read how to write in Java first, and then try to do something for Android.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question