Android UI How to - Implement View.OnClickListener








The following code shows how to implement View.OnClickListener.

Example

//w  w w  .j  ava  2  s.  c  om
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/button"
        android:text="OK"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
</LinearLayout>

Java code

//  ww  w  .j  a va  2  s  .com

package com.java2s.app;

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

import java.util.Date;

public class MainActivity extends Activity implements View.OnClickListener {
    Button btn;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        setContentView(R.layout.activity_main);

        btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(this);
        updateTime();
    }

    public void onClick(View view) {
        updateTime();
    }

    private void updateTime() {
        btn.setText(new Date().toString());
    }
}
null