android通过自定义toast实现悬浮通知效果的示例代码

作者:赖床的猫 时间:2022-08-11 03:23:54 

android通过toast实现悬浮通知效果,如图:

android通过自定义toast实现悬浮通知效果的示例代码

实现的功能:

  •  自定义悬浮弹窗;

  • 点击其他地方该布局不受影响;

  • 可自定义显示时间;

  • 可以设置点击事件;

代码如下:


import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import cn.droidlover.xdroidmvp.router.Router;
import io.slife.wallet.R;
import io.slife.wallet.config.IntentKey;
import io.slife.wallet.ui.NewsFlashDetailActivity;

public class PushToast {
private AppCompatActivity mActivity;
private static PushToast mInstance;
private Toast mToast;
private final int SHOW = 1;
private final int HIDE = 0;
private Object mTN;
private Method mShow;
private Method mHide;
private Field mViewFeild;
private long durationTime = 5*1000;

public static PushToast getInstance() {
if (mInstance == null) {
 mInstance = new PushToast();
}
return mInstance;
}

public void init(AppCompatActivity activity) {
mActivity = activity;
}

public void createToast(String title, String content, Map<String,String> params) {
if (mActivity == null) {
 return;
}
LayoutInflater inflater = mActivity.getLayoutInflater();//调用Activity的getLayoutInflater()
//  LayoutInflater inflater = (LayoutInflater) context.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.view_push_toast, null); //加載layout下的布局
LinearLayout llPushContent = (LinearLayout) view.findViewById(R.id.ll_push_content);
TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
TextView tvContent = (TextView) view.findViewById(R.id.tv_content);
tvTitle.setText(title);
tvContent.setText(content);
mToast = new Toast(mActivity);
mToast.setView(view);
mToast.setDuration(Toast.LENGTH_LONG);
mToast.setGravity(Gravity.TOP, 0, 0);
reflectEnableClick();
reflectToast();
llPushContent.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
  String newsFlashId = params.get("InformationID");
  Router.newIntent(mActivity).to(NewsFlashDetailActivity.class).putString(IntentKey.NEWS_FLASH_ID,newsFlashId).launch();
  handler.sendEmptyMessage(HIDE);
 }
});
if(mShow != null && mHide != null){
 handler.sendEmptyMessage(SHOW);
}else{
 mToast.show();
}
}

private void reflectEnableClick() {
try {
 Object mTN;
 mTN = getField(mToast, "mTN");
 if (mTN != null) {
  Object mParams = getField(mTN, "mParams");
  if (mParams != null
    && mParams instanceof WindowManager.LayoutParams) {
   WindowManager.LayoutParams params = (WindowManager.LayoutParams) mParams;
   //显示与隐藏动画
//     params.windowAnimations = R.style.ClickToast;
   //Toast可点击
   params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
     | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
   //设置viewgroup宽高
   params.width = WindowManager.LayoutParams.MATCH_PARENT; //设置Toast宽度为屏幕宽度
   params.height = WindowManager.LayoutParams.WRAP_CONTENT; //设置高度
  }
 }
} catch (Exception e) {
 e.printStackTrace();
}
}

/**
* 反射字段
*
* @param object 要反射的对象
* @param fieldName 要反射的字段名称
*/
private static Object getField(Object object, String fieldName)
 throws NoSuchFieldException, IllegalAccessException {
Field field = object.getClass().getDeclaredField(fieldName);
if (field != null) {
 field.setAccessible(true);
 return field.get(object);
}
return null;
}

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
 super.handleMessage(msg);
 switch (msg.what) {
  case SHOW:
   handler.sendEmptyMessageDelayed(HIDE, durationTime);
   show();
   break;
  case HIDE:
   hide();
   break;
 }
}
};

public void reflectToast() {
Field field = null;
try {
 field = mToast.getClass().getDeclaredField("mTN");
 field.setAccessible(true);
 mTN = field.get(mToast);
 mShow = mTN.getClass().getDeclaredMethod("show");
 mHide = mTN.getClass().getDeclaredMethod("hide");
 mViewFeild = mTN.getClass().getDeclaredField("mNextView");
 mViewFeild.setAccessible(true);
} catch (NoSuchFieldException e) {
 e.printStackTrace();
} catch (IllegalAccessException e) {
 e.printStackTrace();
} catch (IllegalArgumentException e) {
 e.printStackTrace();
} catch (NoSuchMethodException e1) {
 e1.printStackTrace();
}
}

public void show() {
try {
 //android4.0以上就要以下处理
 if (Build.VERSION.SDK_INT > 14) {
  Field mNextViewField = mTN.getClass().getDeclaredField("mNextView");
  mNextViewField.setAccessible(true);
  LayoutInflater inflate = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  View v = mToast.getView();
  mNextViewField.set(mTN, v);
  Method method = mTN.getClass().getDeclaredMethod("show", null);
  method.invoke(mTN, null);
 }
 mShow.invoke(mTN, null);
} catch (Exception e) {
 e.printStackTrace();
}
}

private void hide() {
try {
 mHide.invoke(mTN, null);
} catch (IllegalAccessException e) {
 e.printStackTrace();
} catch (IllegalArgumentException e) {
 e.printStackTrace();
} catch (InvocationTargetException e) {
 e.printStackTrace();
}catch (NullPointerException ex){
 ex.printStackTrace();
}
}
}

xml布局:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_push_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg_push_message"
android:orientation="vertical">
<TextView
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:text="标题"
android:maxLines="2"
android:ellipsize="end"
android:textStyle="bold"
android:textSize="@dimen/text_size_14" />
<TextView
android:id="@+id/tv_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/black_808080"
android:textSize="@dimen/text_size_13"
android:maxLines="3"
android:ellipsize="end"
android:layout_marginTop="@dimen/margin_large"
android:text="1"/>

</LinearLayout>

点九格式图片:

android通过自定义toast实现悬浮通知效果的示例代码

使用方法:

activity中需要初始化一次:


PushToast.getInstance().init(this);

调用:


PushToast.getInstance().createToast(msg.title,msg.text,umengPushEntity.getExtraMap());

来源:https://www.jianshu.com/p/448abea48e74

标签:android,悬浮,通知
0
投稿

猜你喜欢

  • Java正确使用访问修饰符的姿势

    2021-10-11 09:52:50
  • Android开发之搜索框SearchView用法示例

    2021-10-30 03:40:19
  • 基于StreamRead和StreamWriter的使用(实例讲解)

    2022-09-11 22:12:36
  • 理解maven命令package、install、deploy的联系与区别

    2022-08-09 05:11:39
  • 关于报错IDEA Terminated with exit code 1的解决方法

    2021-06-03 08:33:12
  • spring boot使用thymeleaf跳转页面实例代码

    2021-09-14 09:46:16
  • java 安全 ysoserial CommonsCollections6 分析

    2021-06-04 01:58:14
  • Android RxJava创建操作符Interval

    2023-08-14 01:26:24
  • JDK常用命令jps jinfo jstat的具体说明与示例

    2021-08-09 16:03:30
  • 深入理解Java抽象类

    2022-08-15 09:17:12
  • Android5.0+ CollapsingToolbarLayout使用详解

    2022-07-01 01:20:25
  • ASM的tree api对匿名线程的hook操作详解

    2022-07-16 15:03:30
  • Spring中XML schema扩展机制的深入讲解

    2022-06-29 07:44:15
  • Spring Boot MQTT Too many publishes in progress错误的解决方案

    2023-06-27 02:16:44
  • C#求n个数中最大值和最小值的方法

    2022-04-20 08:00:01
  • C#向线程中传递多个参数的解决方法(两种)

    2022-08-16 19:16:30
  • 详解Android实现定时器的几种方法

    2021-10-17 17:37:17
  • 灵活使用Android中ActionBar和ViewPager切换页面

    2022-07-08 17:20:09
  • 基于mvc5+ef6+Bootstrap框架实现身份验证和权限管理

    2023-07-08 09:25:22
  • C#中使用jieba.NET、WordCloudSharp制作词云图的步骤

    2022-02-10 19:38:49
  • asp之家 软件编程 m.aspxhome.com