Introduction
This article explains CustomToasts in Android. Android Studio is used to create the sample. For this, you will use LayoutInflator to inflate the layout in another layout. For this, you will create the object of LayoutInflator by calling getLayoutInflator() provided by the LayoutInflator. Now get the Layout into the view by calling the inflate method of LayoutInflator.
You will use two XML files, one to hold the layout and another that will be held.
-
getLayoutInflator(): gets the layout object
- inflate(): inflates another layout
Step 1
Create a project like this:
Step 2
Create an XML file and write this:
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- android:paddingBottom="@dimen/activity_vertical_margin"
- tools:context=".MainActivity">
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Custom Toast"
- android:textStyle="bold"
- android:textSize="25dp"
- android:textColor="#f14e23"
- android:layout_centerHorizontal="true"
- />
-
- </RelativeLayout>
Create a Java class file with the following code.
For this, you will use LayoutInflator to inflate the layout in another layout. For this you will create an object of LayoutInflator by calling getLayoutInflator() provided by the LayoutInflator. Now get the Layout into the view by calling the inflate method of LayoutInflator.
- package com.customtoast;
- import android.content.Context;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Gravity;
- import android.view.LayoutInflater;
- import android.view.Menu;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.Toast;
-
- public class MainActivity extends Activity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- LayoutInflater layoutInflater=getLayoutInflater();
- View layout=layoutInflater.inflate(R.layout.second,(ViewGroup)findViewById(R.id.custom_Toast));
- Toast t=new Toast(getApplicationContext());
- t.setDuration(Toast.LENGTH_LONG);
- t.setGravity(Gravity.CENTER_VERTICAL,0,0);
- t.setView(layout);
- t.show();
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
-
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
- }