Xar*_*ren 6 android listener android-fragments
我试图监听 BotomSheetDialogFragment 中的数据或将数据传递到 Fragment 中以更改 Fragment 上的某些内容(就像选择器一样)。
我尝试使用 getTargetFragment 实例化侦听器,但出现编译器错误 Found: 'MyFragment', required: 'android.support.v4.app.Fragment' less..
有什么想法还是我采取了错误的方法?
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;
}
}}
Run Code Online (Sandbox Code Playgroud)
和片段:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
除此之外,它不起作用,该代码有点味道,因为您正在MyBottomSheetDialogFragment与创建它的对象耦合。
正确的方法是启用一个方法void setOnChooseReasonListener(OnChooseReasonListener listener)并MyBottomSheetDialogFragment在创建实例时调用它。
myBottomSheetDialogFragment.setOnChooseReasonListener(this);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6475 次 |
| 最近记录: |