【问题标题】:How to create a dynamic variable name ? Android Studio id name problem如何创建动态变量名? Android Studio id 名称问题
【发布时间】:2021-12-20 03:43:58
【问题描述】:

我正在做 android 并且想要一个一个地获取 id 名称,以便我可以以正确的顺序显示视图上的数据,因此我将 id 保存为 (selected1, selected2, selected3, ...)。实际上,我想在 MainActivity 中为用户在 SecondActivity 中选择的项目命名,然后使用 Intent 在 MainActivity 中取回名称。

但问题是我无法像 MainActivity 的 TextView 那样动态调用 id 名称

int counter = 1;
// to count till which view we put the data,
// numbering is also related to name of id's you can see in image
String str_count = Integer.toString(counter);
String selected = "selected";
String id_name = selected + str_count;
// currently id_name = "selected1", I am going to increase this counter
// so next time we will get the next view

但它告诉我们创建名称为 id_name 的新 id

【问题讨论】:

    标签: java android xml android-studio android-identifiers


    【解决方案1】:

    R.id.* 实际上是一个整数值。可以通过Resources#getIdentifier 方法获取。

    TextView place = findViewById(
        getResources().getIdentifier("selected" + counter, "id", getPackageName())
    );
    

    【讨论】:

    • 你真的解决了我的问题兄弟。谢谢你:)
    猜你喜欢
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 2011-10-27
    • 1970-01-01
    相关资源
    最近更新 更多