我希望能够遍历生成的R文件中的所有字段.
就像是:
for(int id : R.id.getAllFields()){
//Do something with id, like create a view for each image
}
Run Code Online (Sandbox Code Playgroud)
我尝试过反射,但我似乎无法加载R类中包含的特定内部类.所以,例如,这对我不起作用:
Class c = Class.forName("packageName.R.id")
Run Code Online (Sandbox Code Playgroud)
我可以反思R类本身,但我需要id类中的字段.
我也试过查看Resources类,但在那里找不到任何东西.在这种情况下,似乎您可以获取resourceID并获取该id的字符串名称,或者获取字符串名称并获取相应的resourceID.我找不到类似的东西:
int[] Resources.getAllResourceIDs()
Run Code Online (Sandbox Code Playgroud)
也许我错了.或者也许我不应该手动打字,例如:
int[] myIds = {R.id.firstResource, R.id.secondResource}
Run Code Online (Sandbox Code Playgroud)
这种方法的缺点是在使用UI设计器时不够灵活.每当他向XML文件添加新资源时,我都必须更新代码.显然不是太痛苦,但它仍然是好的,似乎它应该是可行的.
编辑:
以下关于ViewGroup.getChildCount()/ ViewGroup.getChildAt()的答案可以正常工作.但是,我还必须找到一种方法来实例化我的XML ViewGroup/Layout.为此,请尝试以下方法:
LayoutInflater li = MyActivity.getLayoutInflater();
ViewGroup vg = (ViewGroup) li.inflate(R.layout.main, null);
Run Code Online (Sandbox Code Playgroud)
小智 6
我发现"Class.forName(getPackageName()+".R $ string");" 可以让你访问字符串资源,也应该适用于id,drawable,exc.
然后我使用这样的类:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
您对我的评论的回复帮助我更好地了解了您要做的事情.
您可以使用ViewGroup#getChildAt和ViewGroup#getChildCount遍历ViewGroup视图层次结构中的各种s instanceof并对返回的Views 执行检查.然后,您可以执行任何操作,具体取决于子视图的类型以及它们在层次结构中的位置.
| 归档时间: |
|
| 查看次数: |
7558 次 |
| 最近记录: |