2010-07-28 10 views
14

¿Cómo puedo hacer una matriz que se ocupa de algunas de mis imágenes para que pueda usarlo como esto ?:Android: ¿Cómo puedo hacer una matriz Drawable?

ImageView.setImageResource(image[1]); 

Espero haberme explicado bien ...

+1

echar un vistazo a esta [Android almacenar R.drawable . identificadores en matriz XML] [1], usa matriz tipada en array.xml. [1]: http://stackoverflow.com/questions/6945678/android-storing-r-drawable-ids-in-xml-array – hayi

+0

@HaYi Gracias usted es muy impresionante. –

Respuesta

50

Para hacer eso, usted don' Quiero una matriz de Drawable, solo una matriz de identificadores de recursos, porque 'setImageResource' toma esos identificadores. ¿Qué tal esto:

int[] myImageList = new int[]{R.drawable.thingOne, R.drawable.thingTwo}; 
// later... 
myImageView.setImageResource(myImageList[i]); 

O para una versión de tamaño variable:

ArrayList<Integer> myImageList = new ArrayList<>(); 
myImageList.add(R.drawable.thingOne); 
// later... 
myImageView.setImageResource(myImageList.get(i)); 
+0

¡Muchas gracias! =) – JoeyCK

+0

Gracias maestro :) – TheOnlyAnil

+0

¿Cómo lograr la adición de imágenes a un int [] pero tienen que buscar a través de todos los archivos y añadir en lugar de nombrar explícitamente cada archivo para agregar? –

9

En primer lugar usted tiene que conseguir todos los ID de dibujable de sus imágenes con el siguiente método:

int android.content.res.Resources.getIdentifier(String name, String defType, String defPackage) 

Para ejemplo, se podía leer todos los ID de dibujable en un bucle:

int drawableId = resources.getIdentifier("picture01", "drawable", "pkg.of.your.java.files"); 
              picture02... 
              picture03... 

..y luego guardarlos en una serie de mapas de bits:

private Bitmap[] images; 
images[i] = BitmapFactory.decodeResource(resources, drawableId); 

Ahora usted es capaz de utilizar sus imágenes como matriz.

1

con respecto a @Bevor, puede utilizar getResources() método en lugar de android.content.res.Resources así:

ArrayList<Integer> imgArr = new ArrayList<Integer>(); 

    for(int i=0;i<5;i++){ 

     imgArr.add(getResources().getIdentifier("picture"+i, "drawable", "pkg.of.your.java.files")); 
    } 

Uso:

imageView.setImageResource((int)imgArr.get(3)); 
0
String[] arrDrawerItems = getResources().getStringArray(R.array.arrDrawerItems); // Your string title array 

// You use below array to create your custom model like 
TypedArray arrDrawerIcons = getResources().obtainTypedArray(R.array.arrDrawerIcons); 

for(int i = 0; i < arrDrawerItems.length; i++) { 
    drawerItemDataList.add(new DrawerItemModel(arrDrawerItems[i], arrDrawerIcons.getResourceId(i, -1), i == 0 ? true : false)); 
} 
drawerItemAdapter = new DrawerItemAdapter(this, drawerItemDataList); 
mDrawerList.setAdapter(drawerItemAdapter); 
Cuestiones relacionadas