Tuesday, February 25, 2014

Button OnClick Event Handling In Android Using XML file

Hi friends it is observed that sometimes it observed that may of the events occur at button click, so in java we use OnClickListener to handle these events. As android uses java it also uses the similar syntax. Due to this the size of code increases so we can make proper use the .xml file provided to us where we can connect all the attributes of the layout as we need.


We just have to follow some simple steps:
        1.     Create an android project and add some button on to it. For example if I want to add two numbers then I will call the add() function on button click.
         2.     To do so we have to edit the following files:
a.     MainActivity.java
b.     activity_main.xml
      3.     Now open the MainActivity.java and type the new function of add() as shown below:
package com.example.calculator;

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

@SuppressLint("ShowToast")
public class MainActivity extends Activity {
EditText num1,num2;

  protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
      
         num1 = (EditText)findViewById(R.id.editText1);
         num2 = (EditText)findViewById(R.id.editText2);
     }
     public void add(View v)
     {
          int a = Integer.parseInt(num1.getText().toString());
          int b = Integer.parseInt(num2.getText().toString());
          int c;
          c= a + b;
          Toast.makeText(getApplicationContext(), "Sum Is :- " + c , 1).show();
     }
     public boolean onCreateOptionsMenu(Menu menu) {
          // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.main, menu);
          return true;
     }
}




      4.     Now edit the code of the button that is added in your activity_main.xml as shown below:
<Button
        android:id="@+id/button1"
        style="@style/AppBaseTheme"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="30dp"
        android:onClick="add"

        android:text="@string/Calculate" />
SO we can optimize the code using xml files.

No comments:

Post a Comment