Friday, September 2, 2011

android:onClick - define callback method when a View clicked, in XML layout.

A callback method can be defined in XML layout file, using "android:onClick". It define the name of the method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View.




android:onClick - define callback method when a View clicked, in XML layout.




<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:onClick="onClick"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 2"
android:onClick="onClick"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 3"
android:onClick="onClick"
/>
</LinearLayout>





package com.exercise.AndroidOnClick;


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

public class AndroidOnClickActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

public void onClick(View view){
Toast.makeText(AndroidOnClickActivity.this,
"onClick:\n" + view.toString(),
Toast.LENGTH_LONG).show();
}
}





No comments:

Post a Comment