第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > android中自定义 toast Android自定义Toast

android中自定义 toast Android自定义Toast

时间:2019-09-21 00:05:25

相关推荐

android中自定义 toast Android自定义Toast

在开发中toast会经常用到,但是每个品牌的手机toast的展示效果是不同的,为了达到统一的效果,并且根据我们的喜好来制定toast,就需要自定义Toast.

先看使用

IToast.show("这是一个土司哦");

IToast.png

关键代码

Toast toast = new Toast(context);

//设置Toast要显示的位置,水平居中并在底部,X轴偏移0个单位,Y轴偏移70个单位,

toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 70);

//设置显示时间

toast.setDuration(show_length);

toast.setView(view);

toast.show();

xml布局

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:orientation="vertical">

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:background="@drawable/toast_shape">

android:id="@+id/toast_tv"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerInParent="true"

android:layout_marginBottom="10dp"

android:layout_marginLeft="20dp"

android:layout_marginRight="20dp"

android:layout_marginTop="10dp"

android:gravity="center"

android:text="一段很长的测试文字"

android:textColor="#fff"

android:textSize="18sp"/>

android:id="@+id/toast_iv"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:src="@mipmap/cofe"/>

自定义Toast,并简单封装

package com.example.chenzhen.isimpledemo.helper;

import android.content.Context;

import android.view.Gravity;

import android.view.LayoutInflater;

import android.view.View;

import android.widget.ImageView;

import android.widget.TextView;

import android.widget.Toast;

import com.example.chenzhen.isimpledemo.IApplication;

import com.example.chenzhen.isimpledemo.R;

/**

* =================中康================

*

* @Author: 陈振

* @Email : 1866376@

* @Time : /8/17 11:24

* @Action :自定义的toast工具类

* 1-自定义样式

* 2-内部自动获取上下文

*

* =================中康================

*/

public class IToast {

/**

* 展示toast==LENGTH_SHORT

*

* @param msg

*/

public static void show(String msg) {

show(msg, Toast.LENGTH_SHORT);

}

/**

* 展示toast==LENGTH_LONG

*

* @param msg

*/

public static void showLong(String msg) {

show(msg, Toast.LENGTH_LONG);

}

private static void show(String massage, int show_length) {

Context context = IApplication.getGlobalContext();

//使用布局加载器,将编写的toast_layout布局加载进来

View view = LayoutInflater.from(context).inflate(R.layout.toast_layout, null);

//获取ImageView

ImageView image = (ImageView) view.findViewById(R.id.toast_iv);

//设置图片

image.setImageResource(R.mipmap.cofe);

//获取TextView

TextView title = (TextView) view.findViewById(R.id.toast_tv);

//设置显示的内容

title.setText(massage);

Toast toast = new Toast(context);

//设置Toast要显示的位置,水平居中并在底部,X轴偏移0个单位,Y轴偏移70个单位,

toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 70);

//设置显示时间

toast.setDuration(show_length);

toast.setView(view);

toast.show();

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。