gpt4 book ai didi

Android:以编程方式遍历资源 ID

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:29:06 24 4
gpt4 key购买 nike

我希望能够遍历生成的 R 文件中的所有字段。

类似于:

for(int id : R.id.getAllFields()){
//Do something with id, like create a view for each image
}

我试过反射,但我似乎无法加载包含在 R 类中的特定内部类。因此,例如,这对我不起作用:

Class c = Class.forName("packageName.R.id")

我可以反射(reflection) R 类本身,但我需要 id 类中的字段。

我也尝试查看 Resources 类,但在那里找不到任何东西。在那种情况下,您似乎可以获取 resourceID 并获取该 id 的字符串名称,或者获取字符串名称并获取相应的 resourceID。我找不到类似的内容:

int[] Resources.getAllResourceIDs()

也许我做错了。或者也许我不应该抗拒将它们全部手动输入,例如:

int[] myIds = {R.id.firstResource, R.id.secondResource}

这种方法的缺点是在与我的 UI 设计师合作时不够灵活。每当他向 XML 文件添加新资源时,我都必须更新代码。显然不会太痛苦,但拥有它仍然很好,而且看起来应该可行。

编辑:

下面关于 ViewGroup.getChildCount()/ViewGroup.getChildAt() 的答案工作正常。但是,我还必须找到一种方法来实例化我的 XML ViewGroup/Layout。为此,请尝试类似的操作:

LayoutInflater li = MyActivity.getLayoutInflater();
ViewGroup vg = (ViewGroup) li.inflate(R.layout.main, null);

最佳答案

我发现“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;
}
}

关于Android:以编程方式遍历资源 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3545196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com