Tuesday, 3 December 2013

Custom Toast

So back to blogging after a long time with a lot new stuff.

This time we are making a CUSTOM toast designed completely by you.
This is what will appear as a toast when you will click the button.


First create a button in the native layout file to trigger the toast.

<Button
        android:id="@+id/buttonShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Show Custom Toast" />


After that create a new layout file in the same folder named "custom_toast.xml". And create an image view and a text view in that layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="10dp"
        />
 
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#DC143C"
        />

</RelativeLayout>


Now the final step is to make changes in the activity file.

package com.codingredefined.customtoast;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity
{
Button button;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.buttonShow);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
LayoutInflater inflater=getLayoutInflater();
View layout=inflater.inflate(R.layout.custom_toast,(ViewGroup)findViewById(R.id.toast_layout_root));
ImageView image=(ImageView)layout.findViewById(R.id.image);
image.setImageResource(R.raw.reebok);
TextView text=(TextView)layout.findViewById(R.id.text);
Toast toast=new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
});
}

}


The following output should be observed.


No comments:

Post a Comment