Friday, January 9, 2015

How to use Button onClick event in Android

activity_main.xml code snippet

<Button
 android:id ="@+id/push_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Click Me"
 android:textSize="50sp"
 android:onClick="perform_action"
 />
MainActivity.java code snippet

//handle the button click event
//require to import View class
public void perform_action(View v)
{
 //require to import Button class
 Button btn = (Button) findViewById(R.id.push_button);
 //require to import TypedValue class
 //set the button text style bold italic
 btn.setTypeface(btn.getTypeface(), Typeface.BOLD_ITALIC);
 //set the button's new text
 btn.setText("You clicked the button");
}
Imported Class

import android.view.View;
import android.widget.Button;
import android.graphics.Typeface;
-->
More android examples