在APP里设置了沉浸式状态栏以后出现了一个问题,Toast里的文字位置出现了偏移,这时候就需要自定义Toast的样式来将文字设置居中。
public class ToastUtil { private static Toast mToast = null; public static void show(Context context, String message) { show(context, message, Toast.LENGTH_SHORT); } private static Handler mHandler = new Handler(); private static Runnable runnable = new Runnable() { @Override public void run() { if (mToast != null) { mToast.cancel(); } } }; public static void show(Context context, String message, int duration) { mHandler.removeCallbacks(runnable); LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.toast_lay, null); TextView str = (TextView) view.findViewById(R.id.toast_content); str.setAlpha(0.9f); str.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.shape_toast_bg)); str.setText(message); mToast = new Toast(context); mToast.setView(view); mToast.show(); mHandler.postDelayed(runnable, 1500); } }
XML布局R.layout.toast_lay
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="10dp" > <TextView android:id="@+id/toast_content" android:text="aaa" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
Syte样式R.drawable.shape_toast_bg
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <!--颜色--> <solid android:color="@color/chat_select_self"/> <!--内边距--> <!--<padding--> <!--android:bottom="20dp"--> <!--android:left="20dp"--> <!--android:right="20dp"--> <!--android:top="20dp"/>--> <corners android:topLeftRadius="10dp" android:topRightRadius="10dp" android:bottomRightRadius="10dp" android:bottomLeftRadius="10dp"/> <!--设置圆角--> <corners android:radius="10dip"/> <!--stroke设置描边--> <!--<stroke--> <!--android:width="2dp"--> <!--android:color="@android:color/darker_gray"/>--> </shape>
但是这设置不了内边距我很苦恼,设置padding没效果
今天更新下解决方法
出现toast背景与提示文字错位的现象,应该是在style里面theme中加入了
<item name="android:fitsSystemWindows">true</item>
其实这句不需要也可以实现沉浸式的效果,删去之后toast就正常显示了;
但是 删除的话又会 出现标题栏栏置顶和导航栏重叠了
可以在根布局内设置
android:fitsSystemWindows="true"
但是如果我们activity比较多,每一个页面都添加android:fitsSystemWindows="true"
比较麻烦,我们需要改动一下:
在Base类中设置
ViewGroup contentFrameLayout = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT); View parentView = contentFrameLayout.getChildAt(0); if (parentView != null && Build.VERSION.SDK_INT >= 14) { parentView.setFitsSystemWindows(true); }
然后所有的 需要类 继承他就可以了;
然后需要沉浸状态栏的activity的布局文件中就可以把android:fitsSystemWindows="true"
这行代码给省略了!