Breaking News
Loading...
Monday, 22 July 2013

Simple example of Button and OnClickListener

10:08
Basic example of Button and OnClickListener to handle button click:

package com.example.androidbutton;

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

public class MainActivity extends Activity {

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

Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(),
"Button 1 clicked",
Toast.LENGTH_LONG).show();
}});

Button button2 = (Button)findViewById(R.id.button2);
button2.setOnClickListener(button2OnClickListener);
}

OnClickListener button2OnClickListener =
new OnClickListener(){

@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"Button 2 clicked",
Toast.LENGTH_LONG).show();
}};

}


<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android-er.blogspot.com" />

<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1"/>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 2"/>

</LinearLayout>

Simple example of Button


Next:
- Determine event source in event listener

0 comments:

Post a Comment

 
Toggle Footer