我正在尝试开发一个小游戏.
我有一个ViewFlipper在ImageViews中有50张图片(随机频率为4张图片).然后我有4个按钮与相同的4张图片可以出现在ViewFlipper.
任务是在出现右图时单击右键.
(当图片1出现时,必须按下按钮1等等)
- flipper.getCurrentView().getId()
给我“-1”作为Id.但是我想要有“R.drawable.pic1”的Id
我的代码到目前为止
我的装载机方法:
- protected void loadPicturesIntoFlipper() {
- Random generator = new Random();
- pictures = new ArrayList();
- for(int i = 0; i < 50;i++){
- int number = generator.nextInt(4) + 1;
- if(number == 1){
- pic = R.drawable.pic1;
- }
- if(number == 2){
- pic = R.drawable.pic2;
- }
- if(number == 3){
- pic = R.drawable.pic3;
- }
- if(number == 4){
- pic = R.drawable.pic4;
- }
- pictures.add(pic);
- }
- for(int i=0;i<pictures.size();i++)
- {
- setFlipperImage((Integer) pictures.get(i));
- }
- }
我的插入方法:
- private void setFlipperImage(int res) {
- image = new ImageView(getApplicationContext());
- image.setBackgroundResource(res);
- flipper.addView(image);
- }
我的检查方法:
- protected void check(int number,int id) {
- int code = 0;;
- if(number == 1){
- code = R.drawable.button_tip_finder;
- }
- if(number == 2){
- code = R.drawable.button_about_us;
- }
- if(number == 3){
- code = R.drawable.button_power_calculator;
- }
- if(number == 4){
- code = R.drawable.button_powerpedia;
- }
- if(code == id){
- test.setText(""+id);
- }
- else{
- test.setText(""+id);
- }
- }
我称之为:
- button1.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- check(1,flipper.getCurrentView().getId());
- flipper.showNext();
- }
- });
解决方法
像这样做:
- private void setFlipperImage(int res) {
- image = new ImageView(getApplicationContext());
- image.setBackgroundResource(res);
- image.setTag(res); //<------
- flipper.addView(image);
- }
接着:
- button1.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- check(1,(Integer)flipper.getCurrentView().getTag());//<----
- flipper.showNext();
- }
- });
- if(number == 1){
- pic = R.drawable.pic1;
- } else if(number == 2){
- pic = R.drawable.pic2;
- } else if(number == 3){
- pic = R.drawable.pic3;
- }