2013-09-25 41 views
0

我想創建自定義視圖和DialogFragment與接口/回調之間的通信。Android通信自定義視圖和DialogFragment與聽衆

自定義視圖:

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

這是工作,但我不知道這是否是好的。我害怕內存泄漏,因爲我從視圖引用靜態方法到對話框片段。

有沒有其他解決方案,比如獲取活動,實例或者投射到什麼地方?

回答

1

您不需要撥打靜態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); 
    } 
}