我试图将数据从BotomSheetDialogFragment中侦听或传递到Fragment中以更改Fragment上的内容(就像选择器一样)。
我已尝试使用getTargetFragment来实例化侦听器,但收到编译器错误发现:' MyFragment',required:' android.support.v4.app.Fragment'少..
任何想法或我采取了错误的做法?
public class MyBottomSheetDialogFragment extends BottomSheetDialogFragment implements View.OnClickListener {
ReportType reportType;
public interface OnChooseReasonListener {
void onChooseReason(ReportType reportType);
}
OnChooseReasonListener listener;
@Override
public void setupDialog(Dialog dialog, int style) {
super.setupDialog(dialog, style);
View contentView = View.inflate(getContext(), R.layout.picker_bottom_sheet_, null);
dialog.setContentView(contentView);
CoordinatorLayout.LayoutParams layoutParams =
(CoordinatorLayout.LayoutParams) ((View) contentView.getParent()).getLayoutParams();
CoordinatorLayout.Behavior behavior = layoutParams.getBehavior();
//get null here!!!:
listener = (OnChooseReasonListener) getParentFragment();// or with getTargetFragment();
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.cool_button:
this.reportType = ReportType.ME;
//trying to execute the lisstener on null
listener.onChooseReason(this.reportType);
dismiss();
break;
}
}}
片段:
public class MyFragment extends Fragment
implements View.OnClickListener,
MyBottomSheetDialogFragment.OnChooseReasonListener {
//....code here
public void showPicker() {
//getting and compiler error Wrong 1st argument type.
// picker. setTargetFragment(MyFragment.this , 300);
picker.show(fm, picker.getTag());
}
@Override
public void onChooseReason(ReportType reportType) {
//not getting here
Log(TAG, "You choose something" + reportType.getValue());
}
}
答案 0 :(得分:1)
除了它不起作用之外,由于你将MyBottomSheetDialogFragment
与创建它的对象耦合,因此该代码闻起来有点香味。
正确的方法是在void setOnChooseReasonListener(OnChooseReasonListener listener)
上设置方法MyBottomSheetDialogFragment
,并在创建实例时调用它。
myBottomSheetDialogFragment.setOnChooseReasonListener(this);