【发布时间】:2018-11-18 12:01:57
【问题描述】:
我使用 BottomSheetDialog 并且我必须获得 Behavior 以便可以设置 setBottomSheetCallback() 来处理一些事情。
作为google says,我必须将 Coordinator 放在 parentView 上并为其添加行为。我在 MainActivity(根活动)中定义了 CoordinatorLayout,如下所示:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:tag="coordinatorLayout"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
...
这是尝试从活动中获取:
public void setupDialog(final Dialog dialog, int style) {
CoordinatorLayout coordinatorLayout = getActivity().getWindow().getDecorView();
BottomSheetBehavior behavior = BottomSheetBehavior.from(coordinatorLayout);
我也试过了:
CoordinatorLayout coordinatorLayout = getActivity().getWindow().getDecorView().findViewById(R.id.coordinatorLayout);
//this is point to the coordinatorView
BottomSheetBehavior behavior = BottomSheetBehavior.from(coordinatorLayout);
//But this returns same error that "The view is not a child of CoordinatorLayout"
如您所见,我通过了协调器布局,但方法无法在其中找到行为。 我还应该提到使用 BottonSheetDialog 的要点:
- 我这样展示我的 BottonSheetFragments:
- 我在 OnCreateView 中(不是在 setupDialog() 中)增加了我的 BottomSheetDialog,以便在其中添加 View Pager。您可能知道,如果您在 onSetupDialog() 中膨胀视图,ViewPager 不会附加到 BottonSheetDialog。
我无法获得父级 CoordinatorLayout 的行为。 在我的 bottonSheetDialog 中,我尝试了这些方法,但它们都不起作用,我得到 "The view is not a child of CoordinatorLayout" 错误。
第 1 点的代码:
MyFragment myFragment= MyFragment.getInstance(bundle);
myFragment.show(fragment.getChildFragmentManager(),"tag");
第 2 点的代码:
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,@Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_bottomsheet, null, false);
return rootView;
}
【问题讨论】:
-
BottomSheetDialog有点奇怪。它实际上并未添加到您的CoordinatorLayout。它以透明背景全屏显示,并在内部设置了自己的CoordinatorLayout,并将底部工作表添加到其中。它还在上面设置了自己的私有BottomSheetCallback,你不能真正干涉它。你可以用BottomSheetBehavior设置你自己的View吗? -
实际上,现在我再次查看源代码,回调所做的唯一事情是
cancel()DialoginonStateChanged()ifnewState == BottomSheetBehavior.STATE_HIDDEN,你可以在你的自己的回调。如果你想试试这个,在BottomSheetDialog上调用findViewById(R.id.design_bottom_sheet)会给你内部FrameLayout有BottomSheetBehavior。 -
@MikeM。让我检查一下。
-
不,特别是
R.id.design_bottom_sheet。它是BottomSheetDialog中内部底部工作表FrameLayout的ID。它在设计库中定义。您无需定义该 ID。 -
谢谢。很用满。我想现在你可以发布答案了。
标签: android android-coordinatorlayout behavior