Я хочу создать свой собственный тост с нуля. Это означает, что я не хочу использовать класс Android в любом аспекте. Мой тост будет реализован в MainActivity и вызывается EventBus из любого места приложения. В моем приложении только одно действие (MainActivity) и множество фрагментов в виде экранов. В моем тосте я хочу реализовать функциональность, аналогичную тосту Android (например, скрыть через 3 секунды, создать очередь, когда в один и тот же момент появляется много тостов и т. Д.), Но я не хочу использовать класс андроида Toast
.
Интересно, как лучше приготовить собственный тост? Создать фрагмент? Посмотреть? Есть еще идеи?
Спасибо за помощь.
Всего 2 ответа
Хорошо, здесь вы можете создать собственный тост, например, зеленый фон с тостом успеха или красный фон с тостом ошибки. Просто следуйте инструкциям шаг за шагом:
Сначала скопируйте и вставьте данные две функции в файл kotlin вне объявления класса, чтобы вы могли получить доступ из любого места в вашем проекте.
fun showErrorToast(context: Context, message: String) {
val parent: ViewGroup? = null
val toast = Toast.makeText(context, "", Toast.LENGTH_LONG)
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val toastView = inflater.inflate(R.layout.toast_custom_error, parent)
toastView.errorMessage.text = message
toast.view = toastView
toast.show()
}
fun showSuccessToast(context: Context, message: String) {
val parent: ViewGroup? = null
val toast = Toast.makeText(context, "", Toast.LENGTH_LONG)
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val toastView = inflater.inflate(R.layout.toast_custom_success, parent)
toastView.successMessage.text = message
toast.view = toastView
toast.show()
}
Затем создайте два файла макета XML с именами «toast_custom_error» и «toast_custom_success», затем скопируйте и вставьте эти два кода XML-макета в эти файлы.
"Toast_custom_error"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:orientation="vertical"
android:background="@drawable/rounded_bg_error"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/errorMessage"
android:textColor="#FFFFFF"
android:textSize="16sp"
android:gravity="center"
android:layout_marginStart="12dp"
android:layout_marginEnd="12dp"
android:layout_marginTop="12dp"
android:layout_marginBottom="12dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
"Toast_custom_success"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:orientation="vertical"
android:background="@drawable/rounded_bg_success"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/successMessage"
android:textColor="#FFFFFF"
android:textSize="16sp"
android:gravity="center"
android:layout_marginStart="12dp"
android:layout_marginEnd="12dp"
android:layout_marginTop="12dp"
android:layout_marginBottom="12dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Затем создайте два нарисованных XML-файла с именами «rounded_bg_error» и «rounded_bg_success» и вставьте в них следующие коды:
"Rounded_bg_error"
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="5dp"/>
<solid android:color="#F81616" />
</shape>
"Rounded_bg_success"
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="5dp"/>
<solid android:color="#B2FF59" />
</shape>
Наконец, вызовите две вышеупомянутые функции из любой точки вашего проекта, как вам нужно:
Из фрагмента ->
showErrorToast(requireContext(), "Your Error Message")
showSuccessToast(requireContext(), "Your Success Message")
Из деятельности ->
showErrorToast(this, "Your Error Message")
showSuccessToast(this, "Your Success Message")
customt_toast.xml
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootId"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>
</FrameLayout>
По вашему мнению:
View toastLayout = getLayoutInflater().inflate(R.layout.custom_toast,
(R.id.rootId));
TextView textView = (TextView) layout.findViewById(R.id.textView);
textView.setText("blah blah");
Toast toast = new Toast(context);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(toastLayout);
toast.show();