【问题标题】:Android - How to store array of classes in res xmlAndroid - 如何在 res xml 中存储类数组
【发布时间】:2019-10-30 02:28:29
【问题描述】:

我想将类列表存储在我 res 上的 xml 中,这样我就可以只使用索引来全局使用它。

<resources>
    <array name="array_class">
        <class>Dashboard.class</class>
    </array>
</resources>

在我的活动中

int index = x; // i get the the index from database
TypedArray arrayClass = getActivity().getResources()
        .(R.array.array_class);
Class myClass = (Class) arrayClass.getString(index);

它给我一个错误,无法将 String 转换为 Class。 是的,我知道,我不能那样做。那么如何在 res 上存储类数组的正确方法呢?或任何其他方式来全局调用 Class[] 值??

【问题讨论】:

  • 如果您觉得我的回答有帮助,请投赞成票

标签: android arrays class typedarray


【解决方案1】:

在你的资源文件中存储所有类的全名,包括包名

<resources>
    <array name="array_class">
        <class>com.example.Dashboard</class>
        <class>com.example.YourOtherClass</class>
    </array>
</resources>

那么在Java代码中,可以通过如下方法检索

try {
    int index = x; // i get the the index from database
    TypedArray arrayClass = getActivity().getResources().(R.array.array_class);
    Class<?> act = Class.forName(arrayClass.getString(index));
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2012-05-19
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多