簡體   English   中英

將偵聽器傳遞給 Android 中的自定義 Fragment

[英]Passing a listener to a custom Fragment in Android

我正在我的應用程序中創建一個視圖尋呼機,並使用一個在其上擴展 Fragment 的類。 當我創建一個實例時,我可以傳遞所有元素(圖像、文本等)並將其與 Bundle 一起存儲以在 onCreate 中使用它。 但是我無法在片段中存儲按鈕的偵聽器。 這是我的課:

public class RegWizardFragmentInfo extends Fragment {

private static final String IMAGE = "image";
private static final String TEXT = "text";
private static final String BUTTON = "buttonText";
private View.OnClickListener buttonCallBack;

private Button button;
private int image;
private int text;
private int buttonText;


public RegWizardFragmentInfo newInstance(int image, int text, int buttonText, View.OnClickListener callback) {

    RegWizardFragmentInfo fragment = new RegWizardFragmentInfo();
    Bundle bundle = new Bundle();
    bundle.putInt(IMAGE, image);
    bundle.putInt(BUTTON, buttonText);
    bundle.putInt(TEXT, text);
    fragment.setArguments(bundle);
    fragment.setRetainInstance(true);
    return fragment;

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.onActivityCreated(savedInstanceState);
    this.image = getArguments().getInt(IMAGE);
    this.text = (getArguments() != null) ? getArguments().getInt(TEXT)
            : -1;
    this.buttonText = (getArguments() != null) ? getArguments().getInt(BUTTON)
            : -1;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.fragment, container, false);
    //Extract all the views and add the image and texts

    return rootView;

}

那么,如何存儲我在 newInstance 中獲得的偵聽器以將其添加到 onCreateView 方法上的按鈕?

感謝您的幫助。

您可以在Fragment使用回調:

public class RegWizardFragmentInfo extends Fragment {

    private Button button;

    private OnClickCallback callback;

    public interface OnClickCallback {
        void onClick();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        callback = (OnClickCallback) context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callback.onClick();
            }
        });
    }
}

並在您的父Activity實現這個新接口

我想您想對各種不同的偵聽器重復使用Fragment 因此,您的方法並不理想,因為您不能為此使用Bundle 更好的方法是使用回調設計模式,例如

public class RegWizardFragmentInfo extends Fragment {

    public interface RegWizardCallback {
        void onClick();
    }
}

您的Activity將實現該接口。 由於Fragment僅存在於 Activity 中,因此您可以使用生命周期方法onAttach()從中獲取回調實例。 它看起來像這樣

public class RegWizardFragmentInfo extends Fragment {
    private RegWizardCallback callback;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            callback = (RegWizardCallback) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement RegWizardCallback ");
        }
    }

    public interface RegWizardCallback {
        void onClick();
    }
}

有了它,您可以簡單地在 Button 的偵聽器內調用callback.onClick

其他答案在onAttach分配偵聽onAttach 雖然這會起作用,但它要求調用Activity (而不是匿名類)實現您的接口。 此外,它強制您將onAttach提供給您的Context onAttach轉換為您的接口實例,這可能導致崩潰並且通常被認為是不良形式。 您可以改為創建一個方法來在您的Fragment設置偵聽器:

public class RegWizardFragmentInfo extends Fragment {

    private OnClickListener mListener;

    public interface OnClickListener {
        void onClick();
    }

    /**
     * Call at any time after this fragment has been constructed.
     */
    public void setListener(OnClickListener listener) {
        mListener = listener;
    }

    /* ...other stuff... */
}

我可以想到這種方法的三個缺點:

  1. 每次要實例化Fragment都需要調用一個額外的方法。
  2. 您不能保證在任何時候都設置了mListener 您可能需要使用空檢查來填充您的Fragment代碼。
  3. 您需要小心確保在生命周期事件(例如屏幕旋轉)之后偵聽器保持設置狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM