欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

android之自定义Toast使用方法

时间:2020-10-03 10:14:34|栏目:Android代码|点击:
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:
复制代码 代码如下:

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();
}
});
}
}

运行效果:
 
?迳竦氖澜缒悴欢?,虫哥的生活你没有,只有程序猿的世界大家才知道。程序猿们,为了自己的精彩世界奋斗吧,努力吧!加油……

上一篇:Android自定义view实现动态柱状图

栏    目:Android代码

下一篇:unity3d发布apk在android虚拟机中运行的详细步骤(unity3d导出android apk)

本文标题:android之自定义Toast使用方法

本文地址:http://www.codeinn.net/misctech/6305.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有