自定义Toas工具类t(二),LayoutInflater加载的布局大小不受控制的解决办法
每天进步一点!!----写在前面
先上效果图
工具类代码如下
public class NewToastUtil { public static void show(Context context, CharSequence message) { //给加载的布局文件的指定父布局,若不指定父布局,则layout所有设置的宽高失去作用 //注:onCreateView()和setContentView()不设置父布局宽高设置也会起作用,因为这俩方法已经默认添加了一个父布局FrameLayout,所以它可以很好的呈现效果 LinearLayout ll=new LinearLayout(context); LayoutInflater inflater = LayoutInflater.from(context); View toastview = inflater.inflate(R.layout.layout, ll); Toast toast =new Toast(context); toast.setGravity(Gravity.CENTER,0,0); TextView tv=toastview.findViewById(R.id.tv); tv.setText(message); toast.setView(toastview); toast.show(); } }
布局文件很简单,如下
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="90dp" android:background="@mipmap/qa" android:layout_height="80dp"> <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_gravity="bottom|center_horizontal" android:text="我不是我没有别瞎说" android:textColor="@color/colorAccent" android:gravity="center_horizontal" android:layout_marginBottom="4dp" android:textSize="6sp" android:layout_height="wrap_content"/> </LinearLayout>
activity调用
findViewById(R.id.aa).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { NewToastUtil.show(MainActivity.this,"请系好安全带"); } });