Current Android Release version:
Version Code: Pie
Version: 9
API level: 28

Customizing Toast In Android


We can customize the toast to display image and text.

For Example: custom_toast.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                     android:id="@+id/custom_toast_layout"
                     android:orientation="horizontal"
                     android:layout_width="fill_parent"
                     android:layout_height="fill_parent"
                     android:padding="8dp" >

       <ImageView android:src="@drawable/image"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:layout_marginRight="8dp" />

      <TextView android:id="@+id/text"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:textColor="#FFF" />
</LinearLayout>


Display Toast:


LinearLayout layout=new LinearLayout(this);
layout.setBackgroundResource(R.color.LightOrange);

TextView tv=new TextView(this);
tv.setTextColor(Color.RED);
tv.setTextSize(15);

tv.setGravity(Gravity.CENTER_VERTICAL);

// set the text you want to show in Toast
tv.setText("My Custom Toast at Bottom of Screen");

ImageView img=new ImageView(this);

img.setImageResource(R.drawable.myimage);

// add both the Views TextView and ImageView in layout
layout.addView(img);
layout.addView(tv);

Toast toast=new Toast(this);
toast.setView(layout);

// Position you toast here toast position is 50 dp from bottom you can give any integral value
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.show();

No comments:

Post a Comment