android toast 简单自定义 && github toasty

时间:2023-01-18 06:37:19

http://www.materialdoc.com/toast/

颜色自定义

getResource().getColor( colorId); 方法废弃
ContextCompat.getColor(context, colorId); 替代方法

Toast toast = Toast.makeText(context, text, duration);

TextView textView = (TextView) toast.getView().findViewById(android.R.id.message);
textView.setTextColor(Color.YELLOW); // 字体颜色

toast.getView().setBackgroundColor(ContextCompat.getColor(context, R.color.indigo)); // 背景颜色

视图自定义

1 toast_text.xml

<?xml version="1.0" encoding="utf-8"?>  
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/txtMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="@drawable/ic_report_problem"
android:drawablePadding="8dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:gravity="center"
android:textColor="@android:color/white"
android:textSize="16dp"
android:text="No connection."
android:background="@color/indigo"/>

2 setView()

Toast toast = new Toast(getApplicationContext());

View view = getLayoutInflater().inflate(R.layout.toast_view, null);

toast.setView(view); // 设置TextView

toast.setDuration(Toast.LENGTH_LONG); // 设置[视图显示]时长

int margin = getResources().getDimensionPixelSize(R.dimen.toast_vertical_margin);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, margin);

toast.show(); // 显示 吐司

方法解析 [简单]

R.layout.transient_notification
这个xml文件,就是toast视图文件

getView()
setView()
操作的都是这个xml文件

    public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
Toast result = new Toast(context);

LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);

result.mNextView = v;
result.mDuration = 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="match_parent"
android:orientation="vertical"
android:background="?android:attr/toastFrameBackground">


<TextView
android:id="@android:id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
android:textAppearance="@style/TextAppearance.Toast"
android:textColor="@color/bright_foreground_dark"
android:shadowColor="#BB000000"
android:shadowRadius="2.75"
/>


</LinearLayout>



github toasty
https://github.com/GrenderG/Toasty

android toast 简单自定义 && github toasty


end