Get Resource Id from ImageView

Billabong picture Billabong · Aug 1, 2013 · Viewed 28.9k times · Source

I am trying to develop a little game.

I have a ViewFlipper which has 50 pictures (random frequence of 4 pictures) in ImageViews. Then I have 4 Buttons with the same 4 pictures which can appear in the ViewFlipper.

The task is to click the right button when the right picture appears. (When Picture 1 appears Button 1 has to be pressed and so on)

My Problem is I don't know how to get the displayed ImageView id.

flipper.getCurrentView().getId() 

gives me "-1" as Id. But I want to have the Id of "R.drawable.pic1"

My code so far:

my Loader-Method:

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));
    }



}

My Insert-Method:

private void setFlipperImage(int res) {

    image = new ImageView(getApplicationContext());
    image.setBackgroundResource(res);
    flipper.addView(image);
}

My Check-Method :

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);
    }


}

I call it like:

 button1.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                check(1,flipper.getCurrentView().getId());
                flipper.showNext();

                }
            });

Answer

M-WaJeEh picture M-WaJeEh · Aug 1, 2013

Do it like this:

private void setFlipperImage(int res) {
    image = new ImageView(getContext());
    image.setBackgroundResource(res);
    image.setTag(res); //<------
    flipper.addView(image);
}

and then:

button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                check(1,(Integer)flipper.getCurrentView().getTag());//<----
                flipper.showNext();
            }
        });

BTW use else in all of your code please, E.g:

 if(number == 1){
      pic = R.drawable.pic1;
 } else if(number == 2){
      pic = R.drawable.pic2;
 }  else if(number == 3){
       pic = R.drawable.pic3;
 }