0

I'm building an android app and I need some advices (I am totally new to java and I've been reading this), I have one button and one image, I need to change the image each time the button is pressed. It is a button that looks like stones and the image is a bowl, I need that each time when the stone button is pressed that the bowl has one more stone in it (I have images of the bowl with 1, 2, 3, ... stones in it). How would I do that? I'm not necessarly asking for the code, just the way I should do it.

4

2 回答 2

3

将您的碗图像放入 Array

int[] Img_array={R.drawable.bowl1,R.drawable.bowl2,......}

& 在按钮的 Onclick 事件中使用其位置

public class MainActivity extends Activity {
             Public int counter=0;
             Button button;
             ImageView imageview;
             int[] Img_array={R.drawable.bowl1,R.drawable.bowl2};

                @Override
             public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
              button=(Button)findViewById(R.id.MyButton);
              imageview=(ImageView)findViewById(R.id.MyImageView);
               button.setOnClickListener(new View.OnClickListener() {

                            public void onClick(View v) {
                                 imageview.setBackgroundResource(Img_array[counter]);
                                      Counter++;
                                 if(counter==Img_array.length())
                                  {
                                        Counter=0;
                                   }


                                      }
                      });
           }
}
于 2013-08-06T09:26:55.633 回答
1

尝试这个

        Button stoneButton=(Button)findViewById(R.id.stoneButton);
        ImageView bowlImageView=(ImageView)findViewById(R.id.bowlImageView);;

         mCount=0;

        ArrayList<Integer> yourImages = new ArrayList<Integer>();
        yourImages.add(R.drawable.image1);
        yourImages.add(R.drawable.image2);
        yourImages.add(R.drawable.image3);


        stoneButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(mCount<yourImages.size())
                {
                bowlImageView.setImageResource(yourImages.get(mCount));
                mCount++;
                }

            }
        });

确保你检查大小,onClick否则它会崩溃。

而且它 setImageResourcesetBackgroundResource在一个ImageView

于 2013-08-06T09:33:57.397 回答