自定义Toast

Android系统默认的Toast十分简洁,使用也非常的简单。但是有时我们的程序使用默认的Toast时会和程序的整体风格不搭配,这个时候我们就需要自定义Toast,使其与我们的程序更加融合。

使用自定义Toast,首先我们需要添加一个布局文件,该布局文件的结构和Activity使用的布局文件结构一致,在该布局文件中我们需设计我们Toast的布局,例如:

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id="@+id/toast_layout_root"
  4. android:orientation="horizontal"
  5. android:layout_width="fill_parent"
  6. android:layout_height="fill_parent"
  7. android:padding="10dp"
  8. android:background="#DAAA"
  9. >
  10. <ImageViewandroid:id="@+id/image"
  11. android:layout_width="wrap_content"
  12. android:layout_height="fill_parent"
  13. android:layout_marginRight="10dp"
  14. />
  15. <TextViewandroid:id="@+id/text"
  16. android:layout_width="wrap_content"
  17. android:layout_height="fill_parent"
  18. android:textColor="#FFF"
  19. />
  20. </LinearLayout>

在这个地方要注意,我们给LinearLayout添加的id属性,在后面的代码中我们需要使用到。在程序中,我们可以通过如下代码创建我们自己的Toast。

  1. /**
  2. *@authorcoolszy
  3. *@bloghttp://blog.youkuaiyun.com/coolszy
  4. */
  5. publicclassMainActivityextendsActivity
  6. {
  7. privateButtonbtn;
  8. @Override
  9. publicvoidonCreate(BundlesavedInstanceState)
  10. {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.main);
  13. btn=(Button)findViewById(R.id.btn);
  14. btn.setOnClickListener(newOnClickListener()
  15. {
  16. @Override
  17. publicvoidonClick(Viewv)
  18. {
  19. //获取LayoutInflater对象,该对象能把XML文件转换为与之一直的View对象
  20. LayoutInflaterinflater=getLayoutInflater();
  21. //根据指定的布局文件创建一个具有层级关系的View对象
  22. //第二个参数为View对象的根节点,即LinearLayout的ID
  23. Viewlayout=inflater.inflate(R.layout.toast_layout,(ViewGroup)findViewById(R.id.toast_layout_root));
  24. //查找ImageView控件
  25. //注意是在layout中查找
  26. ImageViewimage=(ImageView)layout.findViewById(R.id.image);
  27. image.setImageResource(R.drawable.head);
  28. TextViewtext=(TextView)layout.findViewById(R.id.text);
  29. text.setText("自定义Toast演示程序");
  30. Toasttoast=newToast(getApplicationContext());
  31. //设置Toast的位置
  32. toast.setGravity(Gravity.CENTER_VERTICAL,0,0);
  33. toast.setDuration(Toast.LENGTH_LONG);
  34. //让Toast显示为我们自定义的样子
  35. toast.setView(layout);
  36. toast.show();
  37. }
  38. });
  39. }
  40. }

运行效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值