Android Button Click and Android Intent Example

Apps require inputs from the user to take action. Generally, you will have a button that starts processing the user input. So let's begin our discussion about Android Button Click Event and Event Handlers. When you click a button, click event is generated as an object. To handle or to take action on button click, you need a handler that will execute your app logic. There are multiple ways to handle click events but we will discuss only one which is most common among android developers.



Generally an app will have more than one activity. You open one activity from another activity based on some logic or user input. In our case, from the main screen to the game screen when user presses the play button. Below is the code snippet to handle click events -

In Layout file, you have button with the id -

<ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnMathPlay"
            android:src="@drawable/ic_play_arrow_white_36dp"
            android:background="@drawable/roundedbtn"
            android:padding="5dp"
            android:layout_margin="2dp" />

In code, you will handle click event for the button as shown below -

      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnMathPlay = (ImageButton) findViewById(R.id.btnMathPlay); //FIND THE BUTTON
        btnMathPlay.setOnClickListener(new View.OnClickListener() { //SET ON CLICK LISTENER
            @Override
            public void onClick(View v) {
                //YOUR CUSTOM LOGIC ON BUTTON CLICK
            }
        });
     }
As you can see from the code snippet, you first find the button using the unique Id assigned to it. Once you have the button, you set a listener to handle onClick event. You write your code or custom logic of your app inside this onClick(View v) method (Android Studio Auto-completion helps to write this code, just start typing it will auto-complete it for you).

It is same as we say - Hey! I am listening to what they are saying, when they will click on this button, i will inform you so that you can do your thing.

Now you have handled the click event, we can write our code to open the game activity from the main activity. For this we first need to understand what is Intent? Intents are of two types -

1. Explicit Intent.
2. Implicit Intent.

Intent is an object which is used to communicate with Android Operating System. Intent is like a message that you pass onto Android OS for doing some work on your behalf. In other words, you say Hey! Android, Can You Open This Activity For Me? or Hey! Android, I Want To Share This Message Can You Help Me? When you explicitly define your intention then it is Explicit Intent otherwise it is Implicit Intent. Let us take one example to be clear about this -

Explicit Intent - Hey Android! Open this activity for me. Here you are explicitly saying to open a particular activity. This is explicit intent. You have defined what you actually want.

Intent i = new Intent(Context, ClassName); //you specify the class name of the activity you want to open.
startActivity(i);

Implicit Intent - Hey Android! I want to share this message. Can you help me? - In this case you want Android to find all the apps that can share the message. You have not defined any activity for sharing the message. Android will find on its own and give you options to select the app.

Take this scenario - You have created an app to search some products. Now you want to allow user to send email to share some products with their friends or family. Creating an email activity along with your actual app will be a huge task. Why not use the existing Gmail App or Outlook or some other app for sending email? This is where implicit intent comes into play. You ask Android for all the activities that can send email. Android will show you the possible options to choose from.

Intent i = new Intent(Intent.ACTION_SEND); //you specify that you want to send a message
i.setType("text/plain"); // message type is plain text
i.putExtra(Intent.EXTRA_TEXT, YOUR_MESSAGE); // you pass your message as extras in your intent object.
startActivity(intent);

Android passes this intent object to the activity which is opened via intent. You can pass extra values by using intent.putExtra. In onCreate() method of activity, you can call getIntent() to get the intent object and extract the values from the intent object.

protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 String message = getIntent().getStringExtra(KEY);
}

Let's integrate all the things learned so far in the code below where you create a handler for button click event and create implicit and explicit intent with extras using putExtra().

package cheezycode.com.justmaths;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    ImageButton btnMathPlay, btnMathShare, btnMathRate;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnMathPlay = (ImageButton) findViewById(R.id.btnMathPlay);
        btnMathShare= (ImageButton) findViewById(R.id.btnMathShare);
        btnMathRate = (ImageButton) findViewById(R.id.btnMathRate);

        btnMathPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //
                //  Example of Explicit Intent
                //  When you click Play Button on the screen
                //  Game Activity will be started
                //

                Intent i = new Intent(MainActivity.this,GameActivity.class);
                startActivity(i);
            }
        });

        btnMathShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //
                //  Example of Implict Intent
                //  When you click Share Button on the screen
                //  Android will find the activities that allow to share messages.
                //

                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, "Just Maths - Learn Maths. http://www.play.google.com");
                startActivity(intent);
            }
        });

        btnMathRate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //
                //  Simple Toast Message To Display Message For Short Duration
                //  Link that to your app landing page.
                //
                Toast.makeText(MainActivity.this,"Open Google Play landing page",Toast.LENGTH_LONG).show();
            }
        });
    }
}


If you have any query or suggestion. Please let us know. Happy Reading


Comments

  1. explain explicit and implicit clearly..all videos and your script are superb.
    but sorry to say.its not clear

    ReplyDelete
  2. Sir, thank you so much it's really owsome

    ReplyDelete
  3. What is intent spoofing?
    I got that error from Google play store and they can't upload my application on play store because of this reason..
    Plz give suggestions
    Email:ajathod13@gmail.com

    ReplyDelete
  4. sir kindly make videos for youtube by speaking slowly

    ReplyDelete
  5. Hello sir your videos are one of the clearest explanations available on you tube. Thanks you But if possible also make videos on advanced android.

    ReplyDelete

Post a Comment

Hey there, liked our post. Let us know.

Please don't put promotional links. It doesn't look nice :)

Popular posts from this blog

Create Android Apps - Getting Started

Polymorphism in Kotlin With Example