coolszy

业余时间专注于移动开发。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  77 随笔 :: 0 文章 :: 101 评论 :: 21万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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

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

复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id
="@+id/toast_layout_root"
android:orientation
="horizontal"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent"
android:padding
="10dp"
android:background
="#DAAA"
>
<ImageView android:id="@+id/image"
android:layout_width
="wrap_content"
android:layout_height
="fill_parent"
android:layout_marginRight
="10dp"
/>
<TextView android:id="@+id/text"
android:layout_width
="wrap_content"
android:layout_height
="fill_parent"
android:textColor
="#FFF"
/>
</LinearLayout>
复制代码

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

复制代码
/**
*
@author coolszy
* @blog
http://blog.csdn.net/coolszy
*/

public class MainActivity extends Activity
{
private Button btn;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn
= (Button) findViewById(R.id.btn);
btn.setOnClickListener(
new OnClickListener()
{
@Override
public void onClick(View v)
{
//获取LayoutInflater对象,该对象能把XML文件转换为与之一直的View对象
LayoutInflater inflater = getLayoutInflater();
//根据指定的布局文件创建一个具有层级关系的View对象
//第二个参数为View对象的根节点,即LinearLayout的ID
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

//查找ImageView控件
//注意是在layout中查找
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.head);
TextView text
= (TextView) layout.findViewById(R.id.text);
text.setText(
"自定义Toast演示程序");

Toast toast
= new Toast(getApplicationContext());
//设置Toast的位置
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
//让Toast显示为我们自定义的样子
toast.setView(layout);
toast.show();
}
});
}
}
复制代码

运行效果:

演示程序下载:http://u.115.com/file/f1f1a980d8

posted on   coolszy  阅读(2931)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示