Sunday, August 16, 2009

Exercise: Load background to ImageButton, in programmatical approach

In addition to "Load background to ImageButton, using XML", Android support programmatic approach also, using setImageResource().

In this exercise, I implement ImageButton.setOnFocusChangeListener() and ImageButton.setOnClickListener() to handle the background image of the ImageButton. The outcome is same as the "Load background to ImageButton, using XML".



Download and save the three image above to res > drawable folder.

Add a ImageButton in main.xml
<?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"
/>
<ImageButton
android:id="@+id/myImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/android"
/>
</LinearLayout>


Modify the source code to implement setOnFocusChangeListener() and setOnClickListener()
package com.exercise.AndroidImageButton;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.ImageButton;

public class AndroidImageButtonActivity extends Activity {

private ImageButton mImageButton;

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

mImageButton = (ImageButton) findViewById(R.id.myImageButton);

mImageButton.setOnFocusChangeListener(
new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if (hasFocus==true)
{
mImageButton.setImageResource(R.drawable.androidonfocus);
}
else
{
mImageButton.setImageResource(R.drawable.android);
}
}
});

mImageButton.setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mImageButton.setImageResource(R.drawable.androidonclick);
}
});
}
}

No comments: