Reputation: 9548
I am trying to create a communication between a custom View and a DialogFragment with an interface/callback.
Custom View:
public MyDraw extends View implements ColorPickerListener
{
public MyDraw(Context context)
{
super(context);
// ...
MyDialogFragment.setColorPickerListener(this);
}
@Override
public void onColorChanged(int color)
{
// ...
}
}
DialogFragment
public MyDialogFragment extends DialogFragment
{
public interface ColorPickerListener
{
public void onColorChanged(int color);
}
ColorPickerListener colorPickerListener;
public static void setColorPickerListener(ColorPickerListener listener)
{
colorPickerListener = listener;
}
// ....
private void colorSelected(int color)
{
colorPickerListener.onColorChanged(color);
}
}
This is working, but I'm not sure if this is Ok. I am afraid of memory leaks, because I am referencing a static method from View to the dialog fragment.
Is there any alternative solution, like getting the activity, the instance or casting to something?
Upvotes: 0
Views: 491
Reputation: 8978
You don't need to call the static setColorPickerListener
method. You can find your DialogFragment
instance using findFragmentByTag
method and then simply call your setColorPickerListener
(non-static method).
public void showPickerDialog() {
DialogFragment newFragment = new PickerFragment();
newFragment.show(this.getSupportFragmentManager(), "dialogfrag1");
getSupportFragmentManager().executePendingTransactions();
// getting the fragment
PickerFragment df1 = (PickerFragment) getSupportFragmentManager().findFragmentByTag("dialogfrag1");
if (df1 != null) {
df1.registerListener(this);
}
}
Upvotes: 1