Android与侦听器通信自定义视图和DialogFragment

Android与侦听器通信自定义视图和DialogFragment,android,interface,communication,android-dialogfragment,Android,Interface,Communication,Android Dialogfragment,我试图在自定义视图和带有接口/回调的DialogFragment之间创建通信 自定义视图: public MyDraw extends View implements ColorPickerListener { public MyDraw(Context context) { super(context); // ... MyDialogFragment.setColorPickerListener(this); } @Overri

我试图在自定义视图和带有接口/回调的DialogFragment之间创建通信

自定义视图:

public MyDraw extends View implements ColorPickerListener
{
   public MyDraw(Context context)
   {
      super(context);

     // ...

     MyDialogFragment.setColorPickerListener(this);
   }


   @Override
   public void onColorChanged(int color)
   {
      // ...
   }
}
对话框片段

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);
   }
}
这是工作,但我不确定这是否是好的。我担心内存泄漏,因为我正在从视图引用一个静态方法到对话框片段


是否有其他解决方案,如获取活动、实例或强制转换到某个对象?

您不需要调用static
setColorPickerListener
方法。您可以使用
findFragmentByTag
方法找到您的
DialogFragment
实例,然后只需调用
setColorPickerListener
(非静态方法)

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);
    }
}