2015-06-02 69 views

回答

1

您可以通過使用反射在java中完成此操作。

如果你不熟悉它已經,這裏是一個很好的起點programmcreek.com

http://www.programcreek.com/2013/09/java-reflection-tutorial/

簡單地說,作爲一個例子,您可以使用此示例代碼通過R中遍歷您的代碼:

import java.lang.reflect.Field; 

import android.util.Log; 

public class ResourceUtil { 

/** 
* Finds the resource ID for the current application's resources. 
* @param Rclass Resource class to find resource in. 
* Example: R.string.class, R.layout.class, R.drawable.class 
* @param name Name of the resource to search for. 
* @return The id of the resource or -1 if not found. 
*/ 
public static int getResourceByName(Class<?> Rclass, String name) { 
    int id = -1; 
    try { 
     if (Rclass != null) { 
      final Field field = Rclass.getField(name); 
      if (field != null) 
       id = field.getInt(null); 
     } 
    } catch (final Exception e) { 
     Log.e("GET_RESOURCE_BY_NAME: ", e.toString()); 
     e.printStackTrace(); 
    } 
    return id; 
} 

另外,您可以參考這個問題的更深入的瞭解: Android: Programatically iterate through Resource ids

0
  1. 進口Field class

    import java.lang.reflect.Field;

  2. 寫在你的代碼

Field[] ID_Fields = R.drawable.class.getFields(); int[] resourcesArray= new int[ID_Fields.length]; for(int i = 0; i < ID_Fields.length; i++) { try { resourcesArray[i] = ID_Fields[i].getInt(null); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

resourcesArray內容的所有資源文件。

+0

嘿傢伙感謝這些我會盡快嘗試他們,我會馬上回到你身邊! –

相關問題