Create and call function in android same activity

Define private function on android dynamically.

Function is the most useful part for any programming language because with the help of function developer can define various methods, tasks into a single set of instructions and by calling this function you can perform simple defined task. So here is the complete step by step tutorial for Create and call function in android same activity.

android-project-download-code-button

Every function contain three major steps without these steps you can not use function.

  1. Function calling.
  2. Function declaration.
  3. Function body.

What i am doing in this project: I am creating a function and call that function on button click event. So after clicking on button defining function will be called. On function i am simply printing a toast message that ” Function called successfully “.

How to Create and call function in android same activity.

Code for MainActivity.java file.

package com.android_examples.com.functioncalling;

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

public class MainActivity extends Activity {

 Button FunctionCalling;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 FunctionCalling = (Button)findViewById(R.id.button1);
 
 // CALL FUNCTION ON BUTTON CLICK METHOD.
 FunctionCalling.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 // function calling 
 functionCallingExample();
 
 }
 });
 
 }

 // function declaration 
 private void functionCallingExample() {
 
 // function body
 Toast.makeText(MainActivity.this, "function called Successfully", Toast.LENGTH_SHORT).show();
 
 }
}

Code for activity_main.xml layout file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.android_examples.com.functioncalling.MainActivity" >

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text="CLICK HERE TO CALL THE FUNCTION" />

</RelativeLayout>

Screenshot:

Create and call function in android same activity

Click Here To Download Create and call function in android same activity project.

Leave a Reply

Your email address will not be published. Required fields are marked *