自定义Toast

来源:互联网 发布:网络工具书 编辑:程序博客网 时间:2024/06/06 00:43

自定义Toast

相信很多android开发者对Toast都很熟悉,在很多场景都会用到,常用的方法无外乎就是:

Toast.makeText(c, "", Toast.LENGTH_SHORT).show();

第一个是上下文,第二个是toast上显示的文字。我们能操作的就只有这些,当然还可以改变toast的显示位置等,但是我们会想为什么这个toast只能显示文字呢?为什么不可以按照我们自己的意愿改变toast的样式呢。下面我来解释下:
第一:为什么只能显示文字,因为Toast的源码里面只定义了一个只包含TextView的布局文件,它的布局文件路径如下D:/Sdk/platforms/android-25/data/res/layout/transient_notification.xml,代码如下
这里写图片描述
在Toast.makeText方法中对该布局进行填充,代码如下:

public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
Toast result = new Toast(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
result.mNextView = v;
result.mDuration = duration;
return result;
}
注意到这两行代码:
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
给toast布局中的textView设置toast要显示的值。
那么现在我们可以想了,我们是否可以自定义一个布局文件来替换系统的布局文件呢?也就是我们写一个类似于makeText的方法呢?答案是可以的,下面废话不多说,直接上代码:
import android.content.Context;
import android.text.Layout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.a71ant.lyc.R;

/**
* toast帮助类
* @author moon
*
*/
public class ToastUtil {
private static Toast toast = null;
private static TextView textView;
public static void showTips(Context c, String tips )
{
if (c == null) {
return;
}
if (toast == null) {
toast = new Toast(c);
View view = LayoutInflater.from(c).inflate(R.layout.toast_view,null);
toast.setView(view);
textView = (TextView)view.findViewById(R.id.tv_tip);
textView.setText(tips);
toast.setDuration(Toast.LENGTH_LONG);
} else {
textView.setText(tips);
}
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
布局文件过于简单,这里就不贴代码了。

原创粉丝点击