-->

Simple example of Button and OnClickListener

Advertisemen
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

Advertisemen

Disclaimer: Gambar, artikel ataupun video yang ada di web ini terkadang berasal dari berbagai sumber media lain. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini.
Related Posts
Disqus Comments
© Copyright 2017 GENERAL INFO FOR ANDROID DEVELOPMENT - All Rights Reserved - Template Created by goomsite - Proudly powered by Blogger