Monday, August 17, 2015

Android Toast Example

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="#b0ca48"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change BG Color"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.content.Context;


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 = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Change the layout background color
                rl.setBackgroundColor(Color.YELLOW);

                // A toast provides simple feedback about an operation in a small popup

                // Get the application context
                Context context = getApplicationContext();

                // Set the Toast message
                CharSequence text = "Color Changed.";

                // Set the Toast duration
                int duration = Toast.LENGTH_SHORT;

                /*
                    static Toast makeText(Context context, CharSequence text, int duration)
                        Make a standard toast that just contains a text view.
                 */
                Toast toast = Toast.makeText(context, text, duration);

                /*
                    show()
                        Show the view for the specified duration.
                 */
                toast.show();
           }
        });
    }
}
More android examples