0
点赞
收藏
分享

微信扫一扫

Android-基本控件(Toast 全解)


1.回顾

   上篇学习和使用了RatingBar 和 OnRatingBarChangeListener()

2.重点

   (1)借用RationBar

   (2)默认Toast 实现

   (3)改变位置Toast 实现

   (4)给Toast添加图片实现

   (5)自定义布局实现Toast

3.Toast 实现

   3.1 效果图

                                                 

Android-基本控件(Toast 全解)_Toast全解

    3.2 说明

     (1) 采用的是 RatingBar 的 OnRatingBarChangeListener 监听 改变 ,触发 Toast 的调用;

     (2) Toast 中的文本 可以直接复制,也可以来自 string.xml 文件

    3.3 默认Toast实现

 

/**
* 默认 Toast
*
*/
private void ToastShow(){
Toast toast=Toast.makeText(this,"默认Toast",Toast.LENGTH_SHORT);
toast.show();
//缩略写法
//Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
}

    3.4 改变位置的Toast 实现

       只需要设置属性 setGravity() 即可


/**
* 改变位置的Toast
*/
private void ToastChangeGravity(){
Toast toast=Toast.makeText(this,"改变位置的Toast",Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}


    3.5 添加图片的Toast 实现

          (1)拿到Toast 的view对象 ,转换为 LineatLayout 

          (2)动态添加图片

          (3)看注释


/**
* 添加 图片的Toast
*/
private void ToastAddImage(){
//这里的文本可以来自 string.xml 通过 id 来 取值 ,也可以 直接是 文本信息
Toast toast=Toast.makeText(this,R.string.toast_addimg, Toast.LENGTH_SHORT);
//使用 LinearLayout 添加 动态图片
LinearLayout linearLayout=(LinearLayout) toast.getView();
//新建ImageView
ImageView imageView=new ImageView(this);
imageView.setImageResource(R.drawable.img);
//添加给 Toast
//默认的图片在下面,如果添加 第二个参数的话 :可以设置图片的位置
linearLayout.addView(imageView,0);
toast.show();

}


    3.6 自定义Toast实现

     (1)自定义Layout布局文件


<?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:gravity="center"
android:orientation="vertical" >

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/img" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_marginTop="30dp"
android:layout_height="wrap_content"
android:text="我是自定义的toastlayout" />

</LinearLayout>


    (2)转换为View对象

            布局文件转换为View对象 ,有两种方法:

          第一种是通过 View.inflate() 实现 :


View view=View.inflate(this,R.layout.toastlayout,null);

           第二种 通过 LayoutInflater 对象实现:


LayoutInflater layoutInflater=getLayoutInflater().from(this);
View view=layoutInflater.inflate(R.layout.toastlayout,null);


   (3)实例化Toast 设置属性即可


/**
* 完全自定义 Toast
*/
private void ToastToLayout(){
//先将 toastLayout 布局文件转换为 view对象
View view=View.inflate(this,R.layout.toastlayout,null);
//实例化 toast
Toast toast=new Toast(this);
//设置布局
toast.setView(view);
toast.setGravity(Gravity.TOP,0, 0);
toast.show();

}


   


4. 实例demo 免积分下载

    赠送:RatingBar 知识


举报

相关推荐

0 条评论