More than that, this entry will show you how to customize a Toast with your own layout and style!
Firstly, create your desired layout for the custom toast:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/custom_toast_layout" android:background="#99CC00" android:layout_width="match_parent" android:layout_height="wrap_content" > <ImageView android:id="@+id/imgIcon" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:src="@drawable/icon" /> <TextView android:id="@+id/tvMessage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/imgIcon" android:text="Message" android:textColor="#FFFFFF" android:layout_marginLeft="5dp" android:textAppearance="?android:attr/textAppearanceMedium" /> </RelativeLayout>
With those XML code, you will have a toast like this:
In the code behind, we need to handle all the controls in custom layout:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView tvMesage = (TextView)layout.findViewById(R.id.tvMessage);
tvMesage.setText("OMG! This custom toast is awsome!");
Next, create a new Toast object, set the custom View for it and do some settings like gravity, duration:
Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.BOTTOM, 10, 10); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(layout);
Finally, do not forget to show it!
toast.show();
And, tada! Show time!
Source code:
https://drive.google.com/file/d/0BzvV1wN-WHWwdmphRUJHTHdndXM/edit?usp=sharing
Comments powered by Disqus.