系统提供的Toast能够显示String类型的字符串,这其实已经够一部分编程者使用的了,但是有些时候我们希望Toast看起来更美观或者让Toast里面加入一部分功能,这时候就要自定义Toast.自定义的Toast其实很简单,我们只需要在逻辑代码中先创建Toast的对象,然后用布局加载器将布局的视图View加载出来,然后如果需要的话可以再对视图View进行设置(视图也可以在布局文件中设置),然后通过Toast对象的setView()设置视图,setDuration()设置显示时间的长短(Toast.LENGTH_SHORT和Toast.LENGTH_LONG),setGravity(a,b,c)设置显示的位置(a:表示显示的位置Gravity.CENTER等位置,b,c:分别表示显示位置的偏移量)等方法进行自定义Toast的设置,最后一定记得要调用show()方法让Toast显示出来.
具体代码:
布局代码:<?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" >
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
逻辑代码:
View view=LayoutInflater.from(MainActivity.this).inflate(R.layout.layout, null);
TextView tv=(TextView) view.findViewById(R.id.tv);
Toast toast=new Toast(MainActivity.this);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setView(view);
toast.show();//必须要写
原文:http://www.cnblogs.com/flagghost/p/4860893.html