Search

Create custom Toast with layout XML

This example show how to create custom Toast with layout XML, to include a ImageView, fixed text and custom message.


Create the layout XML, layout/layout_mytoast.xml.
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="@android:drawable/screen_background_dark_transparent">

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher_round"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:textSize="14dp"
android:textStyle="italic"
android:text="MY TOAST"
/>
<TextView
android:id="@android:id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:shadowColor="#BB000000"
android:shadowRadius="5"
android:textSize="16dp"
android:textStyle="bold"
/>
</LinearLayout>


</LinearLayout>


Java example:
package com.blogspot.android_er.mytoast2;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

showToast();
}

private void showToast(){
/*
Toast.makeText(MainActivity.this,
"It's default Toast",
Toast.LENGTH_LONG).show();
*/

LayoutInflater inflater = getLayoutInflater();
View toastView = inflater.inflate(R.layout.layout_mytoast, null);
Toast myToast = new Toast(MainActivity.this);
myToast.setView(toastView);
myToast.setGravity
(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,
0, 0);
myToast.setDuration(Toast.LENGTH_LONG);
myToast.setText("It's my Toast with custom layout XML.");
myToast.show();

}
}




Related FYI:
The default layout of Toast should be located at:
...\android-sdk\platforms\<version>\data\res\layout\transient_notification.xml






Bagikan Berita Ini

0 Response to "Create custom Toast with layout XML"

Post a Comment


Powered by Blogger.