I want to call a method from a Fragment inside of the method setPositiveButton() of a AlertDialog used to return a Dialog for a DialogFragment and can't do that.
I have the method doSomething() inside a class named Test that extends of Fragment. Inside of this class I have a inner class that extends of DialogFragment. In the method onCreateDialog is where the problem happens. Look at the code:
public class Test extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.activity_main, null);
return view;
}
public static class SelectDeviceDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
((Test) getTargetFragment()).doSomething();
}
}).create();
}
}
private void doSomething() {}
}
The DialogFragment and Fragment are from the lib android.support.v4.
The error happens because the cast to Test can't be done. How could I call the method doSomething in that case?
Thanks.