因此,对于某些背景,我试图在自定义视图中调用我的片段(托管自定义视图)中的方法。
我尝试过使用接口并在片段中实现它。我也试过在customview中获取片段的实例并以这种方式调用方法。无论出于何种原因,我都会得到无效指针。
方式#1public 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();
}
}
}
});
方法update()在我的片段中被调用,我尝试显示一个toast,但它返回一个空指针。
方式#2在customview的构造函数中获取片段的实例并调用该方法。
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();
}
这也会返回一个空指针....
我的片段是:
public class MultipleChoicePollFragment extends Fragment implements SurveyView.UpdatePolls
我实施的方法是:
@Override
public void update() {
Toast.makeText(getActivity(), "Success", Toast.LENGTH_SHORT).show();
}
答案 0 :(得分:1)
您可以使用侦听器(您的片段)并将其添加到视图(setListener)。或者您可以使用事件总线(GreenRobot,Otto等)。目标是提交一个事件,让某人通过订阅/取消订阅来收听它。
答案 1 :(得分:1)
不要在构造自定义视图时尝试获取它,而是等到onCreateView()
并通过公共方法自己注册片段。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle saved) {
View view = inflater.inflate(...);
SurveyView surveyView = (SurveyView) view.findViewById(...);
surveyView.setUpdatePolls(this);
...
return view;
}
然后您的SurveyView只需要在尝试调用方法之前进行一些空检查(以确保注册某些内容)。
if (updatePolls != null) {
updatePolls.update();
}
答案 2 :(得分:1)
getSupportFragmentManager()
这样可行,但您需要使用curl http://textbelt.com/text -d number=<PHONE NUMBER> -d "message=Doneskiiz"
。