Site icon AndroidRide

Simple Guide: Button onClick XML example in Android

admin
7 years ago

In this post, you will learn how to perform an action using Button and onClick attribute in XML. It is simple and easy to understand. Before creating the project, Let’s know more about android:onClick attribute in Android.

How android:onClick XML attribute works here with Button?

android button onclick - How it works



For detecting tap or button click event in android we can use android:onClick attribute. When users tap the views which hold android:onClick , android looks for the method in the activity. If the exact method found, that will start execution. So, provide a valid method name that lives in hosted activity as the XML attribute value. Not only Button It works for ImageButton, CheckBox, and RadioButton too.

  • 9 Android WebView Example Tutorials that had gone way too far
  • The Beginner’s Guide : AsyncTask in Android tutorial with Example

we can specify onClick attribute just like given below:

android:onClick=”Method_name_in_your_activity”

For better working of the onClick attribute, you must take care of these:

  1. The method name must be the same in value of onClick attribute and in Activity.
  2. The method has to accept a View parameter. The view here means which holds onClick xml attribute or which view was clicked. here, that is button
  3. it needs to return a void value.
  4. the method must be defined as public.

If you don’t obey above ones, most of the time you will end with an exception.

  • 4 Ways to make Android TextView Bold

Let’s create a project, In this project, we will add a Button and TextView, When the user taps the Button it calls a method in the activity depends on android:onClick value and set text in TextView.

We assume that you opened Android Studio.

Step 1

File->New ->New Project

Application Name: OnClick XML Ex

Company Domain: androidride.com

Click Next


Step 2

Select the form factors and minimum SDK

tick the phone and tablet checkbox and choose API 15: Android 4.0.3(IceCream Sandwich) and click Next.


Step 3

Select Empty Activity template

For this project, we just need an empty activity template. So just select the empty activity template and click Next.


Step 4

Create a new empty activity and layout

Next screen prompt for making an activity class file and its layout.

Activity Name: MainActivity

Tick the generate the layout checkbox if it’s not checked.

Layout Name: activity_main

Tick Backward Compatibility checkbox and Click finish.


Step 5

open activity_main.xml and paste the below code

You can drag LinearLayout, Button, and TextView wherever you want and give id, onClick attribute as you want or you can simply paste the below code. The layout just contains the Button and TextView inside LinearLayout.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
	android:gravity="center"
    tools:context=".MainActivity">

   <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:onClick="myMethod"
       android:text="Click Me" />

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/textview"
       />

</LinearLayout>

Now you can see android:onClick value (myMethod) is underlined with red color and gives you an error message that “Corresponding method handler ‘public void myMethod(android.view.View) not found.

This is because we didn’t define the method in our MainActivity class.


Step 6
Define myMethod and set text

Obeying all rules specified earlier, create myMethod() and initialize and set the text to textview.


package com.androidride.buttononclickex;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        }

    public void myMethod(View view)
    {
		//get the textview
		TextView textView=(TextView)findViewById(R.id.textview);
               //set text to textview
               textView.setText("Button clicked");
    }
}

Just run your app.

  • Quick way to make your app

screenshot button onclick xml example - Simple guide Button onclick xml example in android - androidride.com

Click here to show full code

build.gradle


apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.androidride.buttononclickex"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    testImplementation 'junit:junit:4.12'
    
}

colors.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#59b547</color>
    <color name="colorPrimaryDark">#208416</color>
    <color name="colorAccent">#8ce876</color>
</resources>

strings.xml



  <resources>
    <string name="app_name">OnClick XML Ex</string>
</resources>


styles.xml


<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
	android:gravity="center"
    tools:context=".MainActivity">

   <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:onClick="myMethod"
       android:text="Click Me" />

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/textview"
       />

</LinearLayout>

MainActivity.java


package com.androidride.buttononclickex;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        }

    public void myMethod(View view)
    {
		//get the textview
		TextView textView=(TextView)findViewById(R.id.textview);
        //set text to textview
        textView.setText("Button clicked");
    }
}

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidride.onclickxmlex">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

For more information
Button google docs

Download Button OnClick XML Example
Please share this post and your valuable comments will help us to improve.

Categories: Beginner, Button
Leave a Comment

AndroidRide

Back to top
Exit mobile version