Android:是否可以将字符串类型的变量应用于findViewById?

问题描述 投票:-1回答:1

我有一个称为framelayouts_monday的FrameLayout变量的数组类型。

我将变量声明为framelayouts_monday = new FrameLayout[24]

我想减少代码,以便在for循环内使用findViewById声明变量。

为此,我尝试在findViewbyId(R.id.__)内部使用String变量,但是无法以我的方式工作。

如果有任何建议,我想听听。

这是我手动完成的代码

frameLayouts_monday= new FrameLayout[24];

    frameLayouts_monday[0] = root.findViewById(R.id.table_1_2_F);
    frameLayouts_monday[1] = root.findViewById(R.id.table_2_2_F);
    frameLayouts_monday[2] = root.findViewById(R.id.table_3_2_F);
    frameLayouts_monday[3] = root.findViewById(R.id.table_4_2_F);
    frameLayouts_monday[4] = root.findViewById(R.id.table_5_2_F);
    frameLayouts_monday[5] = root.findViewById(R.id.table_6_2_F);
    frameLayouts_monday[6] = root.findViewById(R.id.table_7_2_F);
    frameLayouts_monday[7] = root.findViewById(R.id.table_8_2_F);
    frameLayouts_monday[8] = root.findViewById(R.id.table_9_2_F);
    frameLayouts_monday[9] = root.findViewById(R.id.table_10_2_F);
    frameLayouts_monday[10] = root.findViewById(R.id.table_11_2_F);
    frameLayouts_monday[11] = root.findViewById(R.id.table_12_2_F);
    frameLayouts_monday[12] = root.findViewById(R.id.table_13_2_F);
    frameLayouts_monday[13] = root.findViewById(R.id.table_14_2_F);
    frameLayouts_monday[14] = root.findViewById(R.id.table_15_2_F);
    frameLayouts_monday[15] = root.findViewById(R.id.table_16_2_F);
    frameLayouts_monday[16] = root.findViewById(R.id.table_17_2_F);
    frameLayouts_monday[17] = root.findViewById(R.id.table_18_2_F);
    frameLayouts_monday[18] = root.findViewById(R.id.table_19_2_F);
    frameLayouts_monday[19] = root.findViewById(R.id.table_20_2_F);
    frameLayouts_monday[20] = root.findViewById(R.id.table_21_2_F);
    frameLayouts_monday[21] = root.findViewById(R.id.table_22_2_F);
    frameLayouts_monday[22] = root.findViewById(R.id.table_23_2_F);
    frameLayouts_monday[23] = root.findViewById(R.id.table_24_2_F);

这不起作用,尝试使用for循环并具有与上面的代码相同的功能

for (int i = 0; i <24; i++){
        String frameLayout_ids_1 = "R.id.table_";
        String frameLayout_ids_2 = "_2_F";
        String frameLayout_ids = frameLayout_ids_1 + (i+1) + frameLayout_ids_2;
        frameLayouts_monday[i] = root.findViewById(Integer.parseInt(frameLayout_ids));
    }

还有我得到的这个错误代码NumberFormatException: For input string: "R.id.table_1_2_F"

android arrays android-framelayout
1个回答
0
投票

您可以使用Resources.getIdentifier()以便能够通过字符串操作执行查找。有关更多信息,请参见此问题和答案:Using Android getIdentifier()

或者,您可以使用View Binding以避免首先不得不手动查找视图。

最后,您可以考虑找到一种无需使用id即可找到这些FrameLayout的方法。例如,如果每个FrameLayout是同一个父项LinearLayout的子代,则可以编写如下内容:

LinearLayout parent = findViewById(R.id.parent);

for (int i = 0; i < parent.getChildCount(); ++i) {
    FrameLayout child = (FrameLayout) parent.getChildAt(i);
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.