gpt4 book ai didi

java - 动态资源名称

转载 作者:太空狗 更新时间:2023-10-29 15:40:39 24 4
gpt4 key购买 nike

我想通过 for 循环填充多个 TextView。这不是实际的代码示例,但我希望它足以让您了解我正在尝试做什么。我什至不确定这是否可行,但我希望有人找到了方法。

    TextView dataTV0 = (TextView) v.findViewById(R.id.dataTV0);
TextView dataTV1 = (TextView) v.findViewById(R.id.dataTV1);
TextView dataTV2 = (TextView) v.findViewById(R.id.dataTV2);
TextView dataTV3 = (TextView) v.findViewById(R.id.dataTV3);
TextView dataTV4 = (TextView) v.findViewById(R.id.dataTV4);
TextView dataTV5 = (TextView) v.findViewById(R.id.dataTV5);

String[] data; //This is acquired from another source

for (int i = 0; i < 6; i++){
(String.format("dataTV%d", i).setText(data[i]);
}

最佳答案

我认为一个选择是 Resources.getIdentifier()

for (int i = 0; i < 6; i++){
TextView textView = (TextView) findViewById( getResources().getIdentifier(String.format("dataTV%d", i), "id", getPackageName() ) )
if(textView != null)
textView.setText(data[i]);
}

更新

为了避免过多的函数调用:

TextView textView;
Resources rresources = getResources();
String packageName = getPackageName();

for (int i = 0; i < 6; i++){
textView = (TextView) findViewById( resources.getIdentifier(String.format("dataTV%d", i), "id", packageName ) )
if(textView != null)
textView.setText(data[i]);
}

关于java - 动态资源名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37598926/

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