-2

I hve searched many times but I did not find what i need.

What i need is :

when a user just click the button I want it changed the background image.(user does not need press to the button I need just one click and change the image )

what i did is :

in selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true" 
        android:drawable="@drawable/web_wl" />
    <item android:drawable="@drawable/web" />
</selector>

and in button xml :

  <Button
        android:id="@+id/btn_wb"
        android:layout_width="50dp"
        android:layout_height="50dp"  
        android:background="@drawable/web_selector" />

but this works only a user hold his hand to the button, but I need it works just one click.

thanks in advance

CompEng
  • 7,161
  • 16
  • 68
  • 122

1 Answers1

1

A selector uses the Color State List Resource. I'm not sure there is, in the list of states, the expected behaviour. However, you can achieve this with a click listener event instead of using a selector:

// init a boolean
private boolean isPressed = false; 

// click listener event 
btn_wb.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
        // change the background once 
        if(!isPressed) {
            v.setBackgroundResource(R.drawable.web_wl);
            isPressed = true;
        }
    }
});
Blo
  • 11,903
  • 5
  • 45
  • 99
  • thank you for answer, but I use pageviewer, and how can I change the `setBackgroundResource` from the fragment , because the buttons on mainactivity? – CompEng May 05 '14 at 11:11
  • I don't understand clearly @ErsinGülbahar. You have a ViewPager which uses Fragments but your button is on Activity, right? If not, could you explain a little more please. – Blo May 05 '14 at 11:19
  • Yes in my main activity I have button and I uses viewpager – CompEng May 05 '14 at 11:22
  • Well @ErsinGülbahar, you need to update the background button from the activity... there is no need to do anything with fragments because your button is inside the activity. Just put the above snippet code inside onCreate method from activity. – Blo May 05 '14 at 11:25
  • ok it works just one thing I need , If a person use swipe how can I understand and set backround image? is there any method to detect which tab a person in? – CompEng May 05 '14 at 11:31
  • @ErsinGülbahar, it might help you: [Getting the current position of a ViewPager](http://stackoverflow.com/questions/8258759/getting-the-current-position-of-a-viewpager) and [ViewPager and Fragments Part II](http://tamsler.blogspot.fr/2011/11/android-viewpager-and-fragments-part-ii.html). – Blo May 05 '14 at 11:43