上一次我们详细的讲解了RecyclerView控件的具体使用,可以说该控件使用非常的广泛,不熟悉的有必要花时间认真学习一下,博客链接为https://blog.csdn.net/chenpeixing361/article/details/89296370。这一次我们继续讲解新的知识,Toast和AlertDialog。
Toast
Toast在前面的博客里我们都用的很多,相信大家都有所熟悉和了解,这次我们专门来进行讲解,包含如下内容:①显示消息;②设置显示的位置;③自定义显示内容(比如添加图片);④简单封装。
我们新建ToastActivity活动类,附带的activity_toast.xml文件布局包含四个按钮组件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_toast1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="默认"/>
<Button
android:id="@+id/btn_toast2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="改变位置"/>
<Button
android:id="@+id/btn_toast3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="带图片(自定义)"/>
<Button
android:id="@+id/btn_toast4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="包装过的Toast"/>
</LinearLayout>
运行的界面截图如下:
然后自定义具体的布局文件,用于第三种用法带图片的布局样式,新建的layout_toast.xml文件代码如下:
<?xml version="1.0" encoding="utf-8"?>
<!-- background前两位代表透明度,后6位代表黑色 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#99000000"
android:gravity="center">
<LinearLayout
android:layout_width="200dp"
android:layout_height="200dp"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:id="@+id/iv_toast"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="fitCenter"/>
<TextView
android:id="@+id/tv_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="以梦为马"
android:textColor="@color/colorWhite"
android:layout_marginTop="10dp"/>
</LinearLayout>
</LinearLayout>
该文件包含一个ImageView和一个TextView,具体属性这里不再展开说明,可参照之前写的博客。
接下来就是按钮点击事件的处理了,我们来到ToastActivity,具体的代码如下: