首页 > 解决方案 > 如何在 Java Android 中分配动态名称?

问题描述

您如何使用仅在运行时知道的名称来初始化一个TextView或任何其他Android组件的名称?

例如:

LinearLayout linLayout = (LinearLayout) findViewById(R.id.dynamicLayout);
linLayout.setOrientation(LinearLayout.VERTICAL);

for(int i = 1; i < 5; i++){
            String dynamic_name = "myTextView"+i;
            //Create new textView named dynamically
            TextView dynamic_name = new TextView(this);
            //style textView here etc
            linLayout.addView(dynamic_name);
        }

标签: javaandroid

解决方案


如何初始化 textView 或任何其他 Android 组件的名称,其名称仅在运行时知道?

你不能。

TextView this_variable_changes在编译时定义,而String this_variable_changes在运行时更改。

那么如何根据只能在运行时知道的数字创建可变数量的 textViews 呢?

一旦你TextView在运行时获得了 s 的数量,以编程方式创建那么多TextViews 并将它们添加到布局中。

由于上述原因,您不需要动态名称。您可以做的是将收到的金额映射到相应数量的TextViews,即Map与索引到收到的金额和TextViews 值的键一起使用。


推荐阅读