自定义Toast的实现

1.首先给你的Toast设计一个你需要的布局,在这里我们设计一个包含图片和文字的布局:

Toast的XML布局如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/toast_layout_root"
;  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <ImageView
    android:id="@+id/ivOfToast"
;   android:layout_width="fill_parent"
    android:layout_height="wrap_content"
  />
  <TextView
    android:id="@+id/tvOfToast"
;   android:layout_width="fill_parent"
    android:layout_height="wrap_content"
  />
</LinearLayout>
2.自定义Toast的方法ShowToast(),在需要的地方调用此方法即可:

/*
     * 从布局文件中加载布局并且自定义显示Toast
     */
    private void showToast(){
        //获取LayoutInflater对象,该对象可以将布局文件转换成与之一致的view对象
        LayoutInflater inflater=getLayoutInflater();
        //将布局文件转换成相应的View对象
        View layout=inflater.inflate(R.layout.custome_toast_layout,(ViewGroup)findViewById(R.id.toast_layout_root));
        //从layout中按照id查找imageView对象
        ImageView imageView=(ImageView)layout.findViewById(R.id.ivOfToast);
        //设置ImageView的图片
        imageView.setBackgroundResource(R.drawable.right);
        //从layout中按照id查找TextView对象
        TextView textView=(TextView)layout.findViewById(R.id.tvOfToast);
        //设置TextView的text内容
        textView.setText("This is Toast but cannot be eaten and hello world");
        //实例化一个Toast对象
        Toast toast=new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setView(layout);
        toast.show();
    }

到此,自定义Toast的示例就写完了,个人所写,仅供参考。


你可能感兴趣的:(自定义Toast的实现)