[embedyt] https://www.youtube.com/watch?v=sZ1fLi4QZ-g[/embedyt]
activity_main.xmlMainActivity.javatoast_layout.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.application.customtoast.MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="show toast" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.965" /> </android.support.constraint.ConstraintLayout>
package com.example.application.customtoast; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showToast(); } }); } public void showToast() { LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_root)); TextView toastText = layout.findViewById(R.id.toast_text); ImageView toastImage = layout.findViewById(R.id.toast_image); toastText.setText("This is a different text"); toastImage.setImageResource(R.drawable.ic_toasticon); Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toast_root" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/holo_blue_dark" android:orientation="horizontal" android:padding="8dp"> <ImageView android:id="@+id/toast_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" /> <TextView android:id="@+id/toast_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@android:color/white" android:textSize="16sp" /> </LinearLayout>