Sunday, March 1, 2015

Adding custom view to toast

Create an xml with following content and save it as layout/toast_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/toast_layout_root"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="8dp"
              android:background="#DAAA">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFF"
        android:textSize="20dp"
        />
</LinearLayout>
Then display toast with custom view:
Toast toast = newToast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
LayoutInflater inflater = getLayoutInflater();
// Inflate layout
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
// Update layout with data
((TextView) layout.findViewById(R.id.text)).setText("Hello World");
// Set custom view
toast.setView(layout);
toast.show();

No comments:

Post a Comment