How to Create Android Button Click Event in XML Layout

In most android application, you will notice that most developer always like to get an instance of a button widget and call the setOnClickListener()method of android View to fire a button event.

It is also possible to trigger button click event in XML layout.

To create button click event in XML layout we need to use the button view onClickattribute and assign it the name of the method that will be call when the button is clicked.

activity_xml_button_click.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="24dp"
    android:background="#ededed">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:layout_centerInParent="true"
        android:onClick="startActivity"
        android:text="Start Activity"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:textSize="15sp"/>

</RelativeLayout>

XmlButtonClickActivity.java

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

import com.bluapp.androidview.R;

public class XmlButtonClickActivity extends AppCompatActivity {

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

    public void startActivity(View view){
        startActivity(new Intent(XmlButtonClickActivity.this, MainActivity.class));
    }
}

As you can see from the XML layout, the onClickproperty has a value of startActivitywhich is the name of the method define in the Activity class.

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.