?先上效果图:
前言:
最近想搞一个通知提示,但是由于使用场景限制,最后决定使用Toast来实现通知的提示。虽然Toast可以进行自定义,但是还是达不到自己想要的效果。最后翻来覆去终于找到了解决方法,特此献上!
代码里有一块操作比较骚,通过反射的方式来获取到了Toast的WindowManager,思来想去,佩服了!
源码:
package xx.xx.xx;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import com.starnet.stbsystemservice.R;
import java.lang.reflect.Field;
public class PushToast {
private final Context mContext;
private Toast mToast;
public PushToast(Context context) {
mContext = context;
}
public void createToast(String title, String content) {
if (mContext == null) {
return;
}
LayoutInflater inflater = LayoutInflater.from(mContext);
@SuppressLint("InflateParams") View view = inflater.inflate(R.layout.view_push_toast, null);
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(mContext);
mToast.setView(view);
mToast.setDuration(Toast.LENGTH_LONG);
mToast.setGravity(Gravity.TOP, 0, 0);
initLayoutParams();
}
public void show(){
mToast.show();
}
private void initLayoutParams() {
try {
Object mTN;
mTN = getField(mToast, "mTN");
if (mTN != null) {
Object mParams = getField(mTN, "mParams");
if (mParams instanceof WindowManager.LayoutParams) {
WindowManager.LayoutParams params = (WindowManager.LayoutParams) mParams;
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
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;
}
}
?布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/white"
android:background="#4169E1"
android:textStyle="bold"
android:textSize="24sp" />
<TextView
android:id="@+id/tv_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000"
android:background="#fff"
android:textSize="24sp"/>
</LinearLayout>
</LinearLayout>
使用方法:
PushToast mToast = new PushToast(context);
mToast.createToast("通知: ","您的画质已经是最佳状态!");
mToast.show();
?参考链接:
https://www.jb51.net/article/148988.htmhttps://www.jb51.net/article/148988.htm
|