使用自定义Toast的时候,在layout文件下设置宽度发现无效,怎么设置都是根据内容大小来显示具体宽度要实现的效果如下
自定义Toast代码如下
public class BottomToast extends Toast {
// private static TextView toastTextView;
public BottomToast(Context context) {
super(context);
}
public static Toast makeText(Context context, CharSequence text, int duration){
Toast result = new Toast(context);
//获取LayoutInflater对象
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//获得屏幕的宽度
int width = wm.getDefaultDisplay().getWidth();
//由layout文件创建一个View对象
View view = inflater.inflate(R.layout.layout_bottom_toast, null);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = 16;
TextView toastTextView = (TextView) view.findViewById(R.id.tv_toast);
//设置TextView的宽度为 屏幕宽度
toastTextView.setLayoutParams(layoutParams);
toastTextView.setText(text);
result.setView(view);
result.setGravity(Gravity.BOTTOM, 90, 0);
result.setDuration(duration);
return result;
}
}
布局文件
<?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="@dimen/bottom_toast_height"
android:gravity="center_vertical"
android:background="@drawable/global_snackbar_bg"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_toast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/bottomToastText"
android:text="@string/feedback_succeed"/>
</LinearLayout>