使用自定义Toast 的时候有个坑,你在布局中设置宽高是无效的,必须在代码中动态设置,而且不能设置跟布局的宽高,必须设置第二级布局的LayoutParma。最后还有一个坑,在setGravity的时候务必加一个参数Gravity.FILL_HORIZONTAL,否则之前设置的是不生效的~
以下是布局
<?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:gravity="center"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="217dp"
android:layout_height="86dp"
android:gravity="center"
android:id="@+id/ll_root"
android:background="@drawable/radis_rectangle_black"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
>
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发布成功"
android:textSize="14sp"
android:textColor="@color/white"
/>
<TextView
android:id="@+id/tv_coin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:layout_marginLeft="6dp"
android:textColor="@color/new_text_color"
android:text="+2玛丽"
/>
</LinearLayout>
<TextView
android:id="@+id/tv_msg"
android:layout_marginBottom="12dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="10sp"
android:gravity="center"
android:maxLines="2"
android:text="每天222"
android:textColor="@color/white"
/>
</LinearLayout>
</LinearLayout>
以下是动态设置布局参数
public class MyToast {
Toast toast;
public MyToast(Context context,String title,String coin,SpannableString msg){
View layout = LayoutInflater.from(context).inflate(R.layout.toast, null);
LinearLayout root = layout.findViewById(R.id.ll_root);
TextView tv_title = layout.findViewById(R.id.tv_title);
TextView tv_coin = layout.findViewById(R.id.tv_coin);
TextView tv_msg = layout.findViewById(R.id.tv_msg);
//设置控件的宽高
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DensityUtils.dp2px(context,217),
DensityUtils.dp2px(context,86));
root.setLayoutParams(lp);
//设置数据
tv_title.setText(TextUtils.isEmpty(title)?"":title);
tv_coin.setText(TextUtils.isEmpty(coin)?"":coin);
if (msg==null){
tv_msg.setVisibility(View.GONE);
}else {
tv_msg.setText(msg);
}
//设置toast
toast= new Toast(context);
toast.setDuration(Toast.LENGTH_LONG);
//必须设置Gravity.FILL_HORIZONTAL 这个选项,布局文件的宽高才会正常显示
toast.setGravity(Gravity.CENTER|Gravity.FILL_HORIZONTAL,0,0);
toast.setView(layout);
}
public void show(){
toast.show();
}
}