Question

I have some dynamically declared ImageButtons, these ImageButtons don't have ids' and they are declared in a LinearLayout, I want to create a method to change Images resources of these ImageButtons when called, and as I don't have a predefined ids' for these ImageButtons I'm using the function getChildAt() with the LinearLayout, but getChildAt() doesn't provide setImageResource(), it just provide setBackgroundResource() and this function doesn't make a replacement to the old Image and also doesn't fit at the old Image as it provides a background not an Image Resource, what can I do with that ?

this is my method code :

private void my_method(int drawable) {

        int count = Righter.getChildCount(); // Righter is the LinearLayout
        for (int i = 1; i < count; i++) {
            Righter.getChildAt(i).setBackgroundResource(drawable); // here is where i change the background image 
            Righter.getChildAt(i).setClickable(true);
        }

    }
Était-ce utile?

La solution

getChildAt() returns View. you need to typecast this View to ImageButton and call setImageResource() method...

    ImageButton imageButton = (ImageButton) linearLayout.getChildAt(0);
    imageButton.setImageResource(R.drawable.btnimage1);

Autres conseils

try this

private void my_method(int drawable) {
   int count = Righter.getChildCount(); // Righter is the LinearLayout
   for (int i = 1; i < count; i++) {
       ((ImageButton)Righter.getChildAt(i)).setImageResource(R.drawable.btnimage1);
       Righter.getChildAt(i).setClickable(true);
   }
}

type cast you Righter.getChildAt(i) with ImageButton

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top