Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

android - how to change the image on click of imagebutton?

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

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

1 Reply

0 votes
by (71.8m points)

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"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...