tags:

views:

26

answers:

2

Hi,

I want to create custom ImageButton, but to work like on/ off button. On click on button image to be changed to pressed(until another button is pressed)!

On picture This month button is on , This year off .

How can I create button like this?

Do I need to use and how ?

Thanks

alt text

A: 

Use the selector XML tag to help you achieve this. Here, see this link about StateListDrawables. So their example shows

a button.xml file:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    <item android:state_pressed="true"
      android:drawable="@drawable/button_pressed" /> <!-- pressed -->
    <item android:state_focused="true"
      android:drawable="@drawable/button_focused" /> <!-- focused -->
    <item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector>

and then links an actual button to that xml:

<Button
  android:layout_height="wrap_content"
  android:layout_width="wrap_content"
  android:background="@drawable/button" />
wheaties
I think `ToggleButton` would be better in this case. http://d.android.com/reference/android/widget/ToggleButton.html
Sergey Glotov
@Sergey Glotov the toggle button is the one with a "light" affixed to the middle. If you want your own custom button with custom graphics when you click, you're going to have to go with a selector. I'm often wrong. If you know something more, post a solution. I'd love to see it too. I'm still learning Android myself.
wheaties
But the selector doesn't save its state?
Sergey Glotov
I try different methods and I think Sergey Glotov is right "selector doesn't save its state". My solution is above
Jovan
A: 

Sergey Glotov and wheaties thanks for your help

For every ImageButton I create separate selectors for default and pressed state, I create ImageButton in xml:

                   <ImageButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@drawable/month_button"
                    android:id="@+id/btnMonth"
                    android:onClick=ButonMonthClick"/>

And onClick event for all ImageButton I change background image programmatically:

        btnWeek.setBackgroundResource(R.drawable.week_pressed);
    btnMonth.setBackgroundResource(R.drawable.month_default);

Thant solve my problem!

Jovan
Don't change the resource manually. That's what the selector is for. See @wheaties answer.
Falmarri
But I want "On click on button, image to be changed to pressed(until another button is pressed)" but selector doesn't save its state.
Jovan