为了不浪费你的时间,先看一下效果图。
然后进入实际操作环节。
平时我们使用其他APP时对于评论这快,通常都是点击之后底部弹窗一个窗口,高度是各不相同,而且如果没有占满屏幕的话还可以往上拖,直到吸附在顶部,感觉是挺有意思的,但其实做起来没有那么难,这篇文章就是以一个新手刚接触这个功能的视觉来写的,好了,新建一个项目吧。
BottomDialogDemo建好之后先在app下的build.gradle中添加一个依赖
implementation 'com.google.android.material:material:1.0.0'
添加位置如下图所示,添加只有记得右上角Sync一下,否则不生效的。
然后创建一个弹窗的dialog_bottom_new.xml布局。
代码如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/shape_dialog_bg"> <TextView android:text="弹窗标题" android:gravity="center" android:textColor="#000" android:textSize="16sp" android:padding="16dp" android:layout_width="match_parent" android:layout_height="wrap_content"/> <View android:layout_width="match_parent" android:background="#000" android:layout_height="0.4dp"/> <androidx.core.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:src="@drawable/code" android:layout_width="match_parent" android:layout_height="wrap_content"/> <ImageView android:src="@drawable/code" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> </androidx.core.widget.NestedScrollView> </LinearLayout>
里面的圆角背景shape_dialog_bg.xml是这个
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:topLeftRadius="25dp" android:topRightRadius="25dp" /> <solid android:color="#fff" /> </shape>
里面的图片是这个
然后修改activity_main.xml布局代码,增加一个Button
<Button android:id="@+id/botton_new_bottom" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="doClick" android:text="New Bottom" />
然后在MainActivity中写入一个方法:
public void doClick(View view) { BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(this); View view1 = getLayoutInflater().inflate(R.layout.dialog_bottom_new, null); mBottomSheetDialog.setContentView(view1); mBottomSheetDialog.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundColor(Color.TRANSPARENT); mBottomSheetDialog.show(); }
运行一下:
拜拜~