1

我想在 android 4.2 上按下按钮时连续更改图片此代码仅更改一次

代码:

public void addListenerOnButton() {


    b1 = (Button) findViewById(R.id.b1);

    i = (ImageView) findViewById(R.id.iv);

    b1.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

        while (event.getAction() == MotionEvent.ACTION_DOWN){
                 ii++;
                    if (ii%2==1) i.setImageResource(R.drawable.pic1); else i.setImageResource(R.drawable.pic2);

                    return true;

        }

                return false;

        }

    });

}
4

3 回答 3

2

检查下面的代码。它应该产生你想要的结果

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

    final Button button = (Button) findViewById(R.id.button);
    final ImageView image = (ImageView) findViewById(R.id.image);
    final AnimationDrawable animation = new AnimationDrawable();

    animation.addFrame(getResources().getDrawable(R.drawable.pic1), 200);
    animation.addFrame(getResources().getDrawable(R.drawable.pic2), 200);
    animation.setOneShot(false);

    image.setImageDrawable(animation);
    button.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                animation.start();
                button.setPressed(true);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                animation.stop();
                button.setPressed(false);
            }

            return true;
        }
    });
}
于 2013-03-02T14:01:54.460 回答
0

像这样将图像存储在一个 int 数组中

int imgarr[]={R.drawable.img1,R.drawable.img2,R.drawable.img1,R.drawable.img3};
take an int to maintain count
int mCount=0;


now onClick()
{

img.setImageResource(imgarr[mCount]);

if(mCount<imgarr.length)
mCount++;

else
mCount=0;

}
于 2013-03-02T13:23:26.420 回答
0

你可以试试这个

while (true){

    if(event.getAction() != MotionEvent.ACTION_DOWN){
        break
    }
    ii++;
       if (ii%2==1) i.setImageResource(R.drawable.pic1); else i.setImageResource(R.drawable.pic2);

       return true;

}
于 2013-03-02T13:27:58.367 回答