Подтвердить что ты не робот

Как изменить цвет и цвет сообщения по умолчанию для тостов в фоновом режиме в Android?

Я хочу создать тостовое сообщение с белым цветом фона и черным цветом сообщения. Мое тостовое сообщение:

Toast.makeText(Logpage.this, "Please Give Feedback...", 3000).show();

Я хотел создать его в другом методе, а не в onCreate().

4b9b3361

Ответ 1

Вы можете создать собственное сообщение, как показано ниже:

Toast toast = new Toast(context);
toast.setDuration(Toast.LENGTH_LONG);

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View view = inflater.inflate(R.layout.your_custom_layout, null);
toast.setView(view);
toast.show();

Один текстовый вид, который вы можете поместить в файл макета и задать желаемый фон и цвет текста.

Также вы можете сделать следующее, для которого не нужен дополнительный файл макета:

Toast toast = Toast.makeText(context, R.string.string_message_id, Toast.LENGTH_LONG);
View view = toast.getView();
view.setBackgroundResource(R.drawable.custom_background);
TextView text = (TextView) view.findViewById(android.R.id.message);
/*Here you can do anything with above textview like text.setTextColor(Color.parseColor("#000000"));*/
toast.show();

Ответ 2

Изменить тост цвета без каких-либо дополнительных макетов, 2018

Я обнаружил, что это очень простой способ изменения цвета фактического фона изображения тоста, а также цвета текста, для этого не требуется никаких дополнительных макетов или каких-либо изменений XML:

Toast toast = Toast.makeText(context, message, duration);
View view = toast.getView();

//Gets the actual oval background of the Toast then sets the colour filter
view.getBackground().setColorFilter(YOUR_BACKGROUND_COLOUR, PorterDuff.Mode.SRC_IN);

//Gets the TextView from the Toast so it can be editted
TextView text = view.findViewById(android.R.id.message);
text.setTextColor(YOUR_TEXT_COLOUR);

toast.show();

Ответ 3

Изменить значение по умолчанию Toast Цвет текста и цвет фона Попробуйте Как это сделать.

 Toast toast = Toast.makeText(MainActivity.this, "Please Give Feedback...", Toast.LENGTH_LONG);
 View view = toast.getView();

 //To change the Background of Toast
 view.setBackgroundColor(Color.TRANSPARENT);
 TextView text = (TextView) view.findViewById(android.R.id.message);

 //Shadow of the Of the Text Color
 text.setShadowLayer(0, 0, 0, Color.TRANSPARENT);
 text.setTextColor(Color.BLACK);
 text.setTextSize(Integer.valueOf(getResources().getString(R.string.text_size)));
 toast.show();

Ответ 4

Вы можете настроить собственный тост для Android, используя следующий код

/**
 * ShowToast
 */
public class ShowToast {
    public ShowToast(Context context, String info) {
        Toast toast = Toast.makeText(context, Html.fromHtml("<font color='#e3f2fd' ><b>" + info + "</b></font>"), Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
    }
}

Если вы хотите изменить фон, вы должны использовать пользовательский макет в тосте

Ответ 5

Создайте файл макета toast.xml относительно того, как ваш тост должен выглядеть следующим образом:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/background_dark">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a custom toast."
        android:textColor="@android:color/white"
        android:layout_gravity="center_vertical" />

</LinearLayout>

Чтобы показать тост в файле java, введите код ниже:

public void showCustomAlert()
    {         
        Context context = getApplicationContext();
        // Create layout inflator object to inflate toast.xml file
        LayoutInflater inflater = getLayoutInflater();

        // Call toast.xml file for toast layout 
        View toast = inflater.inflate(R.layout.toast, null);

        Toast toast = new Toast(context);

        // Set layout to toast 
        toast.setView(toast);
        toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,
                0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.show();         
    }

Ответ 6

Toast toast=   Toast.makeText(YOUR ACTIVITY NAME ,Toast.LENGTH_SHORT);
View view =toast.getView();
view.setBackgroundColor(Color.GREEN); //any color your want 
toast.show();

Ответ 7

Версия Kotlin:

 val toast = Toast.makeText(this, getString(R.string.back_again), Toast.LENGTH_SHORT)
 val view = toast.view
 view.background.setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_IN)
 toast.show()

Ответ 8

static void CustomToast(Context context, String text, int duration,
                                    @Nullable Integer backgroundColor,
                                    @Nullable Integer textColor){
        Toast t = Toast.makeText(context,text,duration);
        if (backgroundColor != null)
            t.getView()
                    .setBackgroundTintList(ColorStateList.valueOf(backgroundColor));
        if (textColor != null)
            ((TextView)t.getView().findViewById(android.R.id.message))
                    .setTextColor(textColor);
        t.show();
    }

Ответ 9

Измените цвет тостов по умолчанию и цвет фона в JAVA. Таким способом вы можете изменить цвет сообщения тоста и цвет фона.

        Toast toast=Toast.makeText(MainActivity.this,"Signin button is clicked.",Toast.LENGTH_SHORT);
        View view =toast.getView();
        view.setBackgroundColor(Color.GREEN);
        TextView toastMessage = (TextView) toast.getView().findViewById(android.R.id.message);
        toastMessage.setTextColor(Color.RED);
        toast.show();

Просто измените цвет текста тоста.

        Toast toast = Toast.makeText(getApplicationContext(), "Signup button is clicked.",Toast.LENGTH_SHORT);

        TextView toastMessage=(TextView) toast.getView().findViewById(android.R.id.message);
        toastMessage.setTextColor(Color.BLUE);
        toast.show();

Ответ 10

Добавляя к ответу @AndroidKiller, вы также можете установить gravity и пользовательский TextView среди прочего:

Toast toast = Toast.makeText(context, context.getResources().getString(resID), Toast.LENGTH_LONG);
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE );        
View toastView = li.inflate(R.layout.toast_hint_layout, null);
TextView text = (TextView) toastView.findViewById(R.id.hint_text_tv);
text.setText(resID);
toast.setView(toastView);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toastView.setBackgroundResource(R.drawable.toast_9_patch);          
toast.show();

Обратите внимание, что ваш фоновый ресурс должен быть девять патчей PNG

Вы можете даже поставить ImageView и несколько TextView в XML следующим образом:

<LinearLayout android:id="@+id/layout_root"
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:orientation="horizontal">
    <ImageView
        android:layout_width="32dp"
        android:layout_height="43dp"
        android:src="@drawable/lightbulb"
        />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:orientation="vertical"
        >
        <TextView
            android:id="@+id/hint_text_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ccc"
            android:textSize="14dp"
            />

        <TextView
            android:id="@+id/hint_text_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="(disable hints in preferences)"
            android:textColor="#555"
            android:textSize="11dp"
            />
    </LinearLayout>
</LinearLayout>

Ответ 11

Изменить цвет сообщения по умолчанию и цвет фона в JAVA......

///////Тост сообщения и изменение цвета фона......... Toast toast = Toast.makeText(MainActivity.this, "нажата кнопка входа.", Toast.LENGTH_SHORT);           View view = toast.getView();           view.setBackgroundColor(Color.GREEN);           TextView toastMessage = (TextView) toast.getView(). FindViewById (android.R.id.message);           toastMessage.setTextColor(Color.RED);           toast.show();

///////Просто изменение цвета сообщения........... Toast toast = Toast.makeText(getApplicationContext(), "Нажата кнопка регистрации.", Toast.LENGTH_SHORT);

        TextView toastMessage=(TextView) toast.getView().findViewById(android.R.id.message);
        toastMessage.setTextColor(Color.BLUE);
        toast.show();