java – 将侦听器传递给Android中的自定义片段

前端之家收集整理的这篇文章主要介绍了java – 将侦听器传递给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方法的按钮上呢?

谢谢您的帮助.

解决方法

您可以在片段中使用回调:
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,savedInstanceState);

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

并在您的父Activity中实现此新接口

原文链接:https://www.f2er.com/java/120392.html

猜你在找的Java相关文章