Friday, November 23, 2012

Selector Example in android


Prepare 3 images for button states, and put it into “resource/drawable” folder.
  1. button_normal_green.png – Default image button.
  2. button_focused_orange.png – Display when button is focused, for example, when phone’s keypad is move (focus) on this button.
  3. button_pressed_yellow.png – Display when button is pressed.
Now, create a new XML file in “res/drawable/” folder, in whatever name you want, in this case, we just give a name as “new_button.xml“. This file defined which button state is belong to which image.
Now, you can refer to this button via this Id : @drawable/new_button.
File : res/drawable/new_button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed_yellow"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_focused_orange"
          android:state_focused="true" />
    <item android:drawable="@drawable/button_normal_green" />
</selector>

Open “res/layout/main.xml” file, add a normal button, and attach the background image to above “new_button” via “android:background="@drawable/new_button
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <Button
        android:id="@+id/imageButtonSelector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/new_button" />
 
</LinearLayout>

A normal button with a simple click listener.
File : MyAndroidAppActivity.java
package com.mkyong.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
 
public class MyAndroidAppActivity extends Activity {
 
 Button imageButton;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
 
  addListenerOnButton();
 
 }
 
 public void addListenerOnButton() {
 
  imageButton = (Button) findViewById(R.id.imageButtonSelector);
 
  imageButton.setOnClickListener(new OnClickListener() {
 
   @Override
   public void onClick(View arg0) {
 
    Toast.makeText(MyAndroidAppActivity.this,
     "ImageButton (selector) is clicked!",
     Toast.LENGTH_SHORT).show();
 
   }
 
  });
 
 }
 
}

Run the application.
1. Result, default button. (button_normal_green.png)
normal button
2. Button is focused. (button_focused_orange.png)
button is focused
3. Button is pressed. (button_pressed_yellow.png)
button is pressed

No comments:

Post a Comment