Какой лучший способ создать собственный тост с нуля? - PullRequest
0 голосов
/ 16 января 2020

Я хочу создать свой собственный тост с нуля. Это означает, что я не хочу использовать класс android * 1002. * в любом аспекте. Мой тост будет реализован в MainActivity и будет вызываться EventBus из любого места приложения. В моем приложении только одно действие (MainActivity) и множество фрагментов в виде экранов. В моем тосте я хочу реализовать функциональность, аналогичную android Toast (например, скрыть через 3 секунды, создать очередь, когда в один и тот же момент появляется много тостов и т. Д. c.), Но я не хочу использовать android Toast класс.

Интересно, как лучше приготовить собственный тост? Создать фрагмент? Посмотреть? Любые другие идеи?

Спасибо за помощь.

Ответы [ 2 ]

0 голосов
/ 16 января 2020

Хорошо, здесь вы можете создать собственный тост, например зеленый фон с тостом успеха или красный фон с тостом ошибки. Просто следуйте инструкциям шаг за шагом:

  1. Сначала скопируйте и вставьте данные двух функций в файл 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()
    }
    
  2. Затем создайте два файла макета 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>
    
  3. Затем создайте два нарисованных 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>
    
  4. Наконец, вызовите две вышеупомянутые функции из любой точки вашего проект, как вам нужно, например:

из фрагмента ->

    showErrorToast(requireContext(), "Your Error Message")
    showSuccessToast(requireContext(), "Your Success Message")

из действия ->

    showErrorToast(this, "Your Error Message")
    showSuccessToast(this, "Your Success Message")
0 голосов
/ 16 января 2020

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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...