Monday, August 17, 2015

How to set Toast message display duration in Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#76b3ca"
    >
    <Button
        android:id="@+id/btn_short"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Short Duration Toast"
        />
    <Button
        android:id="@+id/btn_long"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Long Duration Toast"
        android:layout_toRightOf="@id/btn_short"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;


public class MainActivity extends Activity {

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

        // Get reference of widgets from XML layout
        final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        Button btn_short = (Button) findViewById(R.id.btn_short);
        Button btn_long = (Button) findViewById(R.id.btn_long);

        btn_short.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Make the Toast message
                Toast toast = Toast.makeText(
                        getApplicationContext(), // Context
                        "Short Duration Toast Message", // Message
                        Toast.LENGTH_SHORT // Short Duration
                );

                // Show the Toast on app interface
                toast.show();
            }
        });

        btn_long.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Make the Toast message
                Toast toast = Toast.makeText(
                        getApplicationContext(), // Context
                        "Long Duration Toast Message", // Message
                        Toast.LENGTH_LONG // Long Duration
                );

                // Show the Toast on app interface
                toast.show();
            }
        });
    }
}
More android examples