Saturday, January 10, 2015

How to use Button onClickListener 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="30sp"
 />
MainActivity.java code snippet

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

 Button btn = (Button) findViewById(R.id.push_button);
 //set a click listener for button widget

 btn.setOnClickListener(new View.OnClickListener() {
  public void onClick(View v) {
   Button btn = (Button) findViewById(R.id.push_button);
   //change the button initial text
   btn.setText("You clicked the button");
  }
 });
}
Imported Class

import android.view.View;
import android.widget.Button;
More android examples