Android图像按钮随每次点击而变化

时间:2013-08-26 16:52:24

标签: android android-button

我希望我的图像按钮每次单击时都会从一个图像更改为另一个图像。在我的代码中,这仅适用一次,图像更改,按钮不会更改为onClick。

有人可以帮忙吗?

package com.wepromoteme.brapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends Activity {

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

setupPlayPauseButton1();

} 

private void setupPlayPauseButton1() {
    ImageButton btn1 = (ImageButton) findViewById(R.id.play_pause1);

    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            ImageButton btn1 = (ImageButton)
findViewById(R.id.play_pause1);
            btn1.setImageResource(R.drawable.play);
        }
    });
}
}

由于

@ shree202

这是新代码:

public class MainActivity extends Activity {

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

setupPlayPauseButton1();

} 

private void setupPlayPauseButton1() {
    final ImageButton btn1 = (ImageButton) findViewById(R.id.play_pause1);

    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            int i=0;
            if(i%2==0) {
                btn1.setImageResource(R.drawable.play);
            } else {
                btn1.setImageResource(R.drawable.pause);

            }
        }
    });
}
}

由于

1 个答案:

答案 0 :(得分:1)

您应该扩展ImageButton并保持Button的状态。因此,它会将您的点击监听器更改为以下内容:

    @Override
    public void onClick(View v) {
        MyImageButton btn1 = (MyImageButton) findViewById(R.id.play_pause1);
        btn1.toggleState();
        switch(btn1.getState()){
           case 0:
              btn1.setImageResource(R.drawable.play);
              break;
           case 1:
              bt1.setImageResource(R.drawable.stop);
              break;
        }
    }