在自定义视图中调用片段方法 [英] Calling a fragment method inside a custom view

查看:163
本文介绍了在自定义视图中调用片段方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,对于某些背景,我试图在自定义视图中调用我的片段(托管自定义视图)中的方法。

So for some background I've tried to call a method I have in my fragment (that's hosting the custom view) within the custom view.

我尝试过使用接口并在片段中实现它。我也试过在customview中获取片段的实例并以这种方式调用方法。无论出于何种原因,我都会得到无效指针。

I've tried using an interface and implementing it in the fragment. I've also tried getting an instance of the fragment in the customview and calling the method that way. For whatever reason, I get null pointers both ways.

方式#1

public SurveyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setOrientation(VERTICAL);
    options = new ArrayList<>();
    //updatePolls is the interface. 
    updatePolls = new MultipleChoicePollFragment();
}
public interface UpdatePolls {
    void update();
}

然后我在onClickListener中调用该方法:

Then I call the method in an onClickListener:

v.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            for (int p = 0; p < options.size(); p++) {
                                if (options.get(p) == v) {
                                    setAnswers(p);
                                    updatePolls.update();
                                }
                            }
                        }
                    });

方法update()在我的片段中调用,我尝试显示吐司,但它返回使用空指针。

The method update() gets called in my fragment and I try to display a toast, but it returns with a null pointer.

方式#2

在customview的构造函数中获取片段的实例并调用方法。

Get an instance of the fragment in the customview's constructor and call the method.

public SurveyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOrientation(VERTICAL);
        options = new ArrayList<>();
    myActivity = (AppCompatActivity)context;
                myActivity.getFragmentManager().findFragmentByTag("MULTIPLE_CHOICE_POLL_FRAGMENT");
            myActivity.update();
}

这也会返回空指针....

This also returns a null pointer....

我的片段是:

public class MultipleChoicePollFragment extends Fragment implements SurveyView.UpdatePolls

我实施的方法是:

@Override
public void update() {
    Toast.makeText(getActivity(), "Success", Toast.LENGTH_SHORT).show();
}


推荐答案

myActivity = (AppCompatActivity)context;
                myActivity.getFragmentManager().findFragmentByTag("MULTIPLE_CHOICE_POLL_FRAGMENT");

这样可行,但你需要使用 getSupportFragmentManager()

This would work, but you need to use getSupportFragmentManager().

这篇关于在自定义视图中调用片段方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆