gpt4 book ai didi

android - 在自定义 View 中调用 fragment 方法

转载 作者:行者123 更新时间:2023-11-29 17:34:07 25 4
gpt4 key购买 nike

因此,对于某些背景,我尝试在自定义 View 中调用我的 fragment (托管自定义 View )中的方法。

我试过使用接口(interface)并在 fragment 中实现它。我还尝试在自定义 View 中获取 fragment 的实例并以这种方式调用方法。无论出于何种原因,我都得到空指针。

方式#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 中调用该方法:

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

在我的 fragment 中调用了 update() 方法,我尝试显示一个 toast,但它返回一个空指针。

方式#2

在自定义 View 的构造函数中获取 fragment 的实例并调用该方法。

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

这也返回一个空指针....

我的 fragment 是:

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()

关于android - 在自定义 View 中调用 fragment 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31410552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com