Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am make a image button .I need to change the image when I click on image button .Actually it change the background image but only for few seconds .why ?

here is my code

 <ImageButton android:id="@+id/favorite"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:src="@drawable/start"
        android:background="#00ffffff"
        />

<?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/on" /> <!-- pressed -->

    <item android:drawable="@drawable/off" /> <!-- default -->
</selector>

I need to show on image when I click on image button ..? can I write on java side ? can I write on click listener of image button ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
490 views
Welcome To Ask or Share your Answers For Others

1 Answer

That's why you are using a selector for your button background and the image changes depending on the state of the button. If it is pressed the image will be "on" and in its normal state (no pressed and no focused) the image will be "off".

EDIT:

public class MainActivity extends AppCompatActivity {

ImageButton btn;
boolean isPressed;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn = (ImageButton) findViewById(R.id.btn);
    btn.setBackgroundResource(R.drawable.normal);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(isPressed){
                v.setBackgroundResource(R.drawable.normal);
            }else{
                v.setBackgroundResource(R.drawable.pressed);
            }
            isPressed = !isPressed; // reverse
        }
    });


}


  <ImageButton
    android:id="@+id/btn"
    android:text="@string/hello_world" android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...