android-fragments 如何在BottomSheetDialogFragment中显示SnackBar?

ybzsozfc  于 2022-11-13  发布在  Android
关注(0)|答案(4)|浏览(192)

我搜索了很多,但没有找到任何解决方案x1c 0d1x和Snackbar is not working within fragment class没有帮助。我传递了fragment的rootView,也尝试从getActivity传递视图,但它们都不起作用!

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.content_dialog_bottom_sheet, container, false);

Snackbar.make(MyActivity.myTextview, "Hello", Snackbar.LENGTH_INDEFINITE).show();

Snackbar.make(rootView, "Hello", Snackbar.LENGTH_INDEFINITE).show();

return rootView;

}

和我的内容对话框底部工作表:

<RelativeLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:id="@+id/bottomSheetLayout"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:background="@color/background"
   app:behavior_hideable="true"
   app:behavior_peekHeight="180dp"
   app:layout_behavior="@string/bottom_sheet_behavior">

  //some views 

</RelativeLayout>
juud5qan

juud5qan1#

解决方案相当简单。您需要:
1.用CoordinatorLayout Package 对话框布局(如果你想在某个特定视图旁边显示snackbar,就用 Package 来代替)
1.显示snackbar时使用CoordinatorLayout id作为视图。

bmp9r5qi

bmp9r5qi2#

Snackbar.make(
            getDialog().getWindow().getDecorView(),
            "your-string",
            Snackbar.LENGTH_SHORT
    ).show();

将此代码和平添加到您的onCreateView

e3bfsja2

e3bfsja23#

延迟后显示小吃吧:

new Handler().postDelayed(new Runnable() {
  @Override
        public void run() {
            Snackbar.make(rootView, "Hello", Snackbar.LENGTH_INDEFINITE).show();

        }
    },200);
uajslkp6

uajslkp64#

如果您要将Bottomsheet类扩展到BottomSheetDialogFragment(),则可以使用对话框的decorView作为视图。
供参考的示例代码片段:

Snackbar.make(
                            dialog?.window?.decorView,
                            "Press login button to continue",
                            Snackbar.LENGTH_LONG
                        )
                            .setAction("Login") { v: View? ->
                                val intent = Intent(context, DestinationActivityAfterLogin::class.java)
                                startActivity(intent)
                            }.show()

====
如果您使用BottomSheetDialog显示底部表单,则可以使用rootView来弹出snackbar。
供参考的示例代码:

Snackbar.make(
                bsBinding.root.rootView, // bsBinding is view binding object
                "Press login button to continue",
                            Snackbar.LENGTH_LONG
                        )
                            .setAction("Login") { v: View? ->
                                val intent = Intent(context, DestinationActivityAfterLogin::class.java)
                                startActivity(intent)
                            }.show()

希望这将是有用的,同时显示与底部工作表对话框小吃吧。
快乐编码。

相关问题