Thursday 25 July 2013

Image Toast in Android

Leave a Comment
In android we have seen the simple Toast message, that will display simple text. But Today I told you how to display an image along with the toast message.
In this application, on the Button click a simple toast will pop out along with image.
Lets begins with the sample for Image Toast in Android.

Step 1:- activity_main.xml
<LinearLayout 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"
>
<Button
    android:id="@+id/btn_click"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
   android:text="clickme"/>
</LinearLayout>

Step 2:- MainActivity.java
package com.arpit.androidimagetoast;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
    Button btnclick;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnclick = (Button) findViewById(R.id.btn_click);
        btnclick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast imageToast = new Toast(MainActivity.this);
                 // set the layout
                LinearLayout layout = new LinearLayout(getBaseContext());
                layout.setOrientation(LinearLayout.HORIZONTAL);
               // set the text that will be display
                TextView txt = new TextView(getBaseContext());
                txt.setText("hello");
                // set the image from the drawable
                ImageView img = new ImageView(getBaseContext());
                img.setImageResource(R.drawable.user);
                // addview to the layout
                layout.addView(img);
                layout.addView(txt);
                imageToast.setView(layout);
                imageToast.setDuration(Toast.LENGTH_LONG);
                imageToast.show();  
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}


Screenshot_2013-07-25-19-15-03

0 comments:

Post a Comment