简体   繁体   English

Android Studio如何设置字符串ID

[英]android studio how to set string Id

I want to set ID for a dynamically added textview in a loop. 我想为循环中动态添加的textview设置ID。 I found out that the only function they have is setId with int parameter. 我发现他们仅有的功能是带有int参数的setId。 How can we set the ID with string, perhaps like this: 我们如何用字符串设置ID,也许像这样:

LinearLayout linearLayout = findViewById(R.id.linearLayout);
for(int i=0; i<10; i++) {
    TextView textView = new TextView(this);
    textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    textView.setText("Text Number "+i);
    textView.setId("@+id/myTextView"+i); // => Is this possible? This will cause error because setId needs INT type parameter.

    linearLayout.addView(textView);
}

I don't want to use resource file because it's not dynamic. 我不想使用资源文件,因为它不是动态的。 Is it possible? 可能吗?

You cannot set id with char or string . 您不能使用charstring设置id。 Only int will work. 只有int可以工作。 However you can use the setTag() API. 但是,您可以使用setTag() API。 You can later do getTag() or use findViewWithTag 您稍后可以执行getTag()或使用findViewWithTag

No, You can't. 不,你不能。 Only int will work. 只有int可以工作。

This link may help you for details understanding. 此链接可以帮助您了解详细信息。 https://stackoverflow.com/a/30253770/4365240 https://stackoverflow.com/a/30253770/4365240

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM