可以通过编程方式创建视图并使用字符串的值来命名它们吗?

huangapple go评论70阅读模式
英文:

Is it possible to create a views programmatically and name them with the value of a string?

问题

我想将不确定数量的视图添加到另一个视图中。所需的视图数量取决于一个变量。我不希望它有限制。并希望它们的名称按照一系列的方式命名(可能使用字符串的递增值)。这是否可以在程序中实现?

我是编程新手。如果这是一个愚蠢的问题,我很抱歉。

英文:

I want to add an indefinite number of views to another view. How many views are needed depends on a variable. I don't want it to have a limit. And want their names to be in a series (using incrementing values of a string maybe). Is it possible to do this programmatically?

I'm new to programming. Sorry if this is a stupid question.

答案1

得分: 1

以下是翻译好的部分:

"你可能不想这样做。视图很昂贵,添加大量视图将使您的应用要么变得极其缓慢,要么崩溃,如果不是两者兼而有之的话。请考虑使用 RecyclerView 作为这样做的替代方案。RecyclerView 会重复使用和重新绑定有限数量的视图,允许以最少的视图数量在它们之间滚动。

如果视图数量较小(它们在屏幕上占据的空间也小)并且有上限,那么添加视图的技术是可以接受的。在这种情况下,您可以使用 add 函数以编程方式向 ViewGroup 添加视图。但您不能为其命名。您可以为其分配一个 ID,但不建议这样做。而且这实际上不应该是必要的 - 由于您创建了它,您不应该需要在视图层次结构中再次查找它,这是为其命名的主要原因之一。"

英文:

You probably don't want to do that. Views are expensive, adding large numbers of them will either slow your app to a crawl or crash it OOM, if not both. Look into RecyclerView as an alternative to doing that. RecyclerViews reuse and rebind a limited number of views, allowing for scrolling between them with a minimal number of views used.

A technique of adding views is acceptable if the number of views is small (as is their screen real estate) and has a cap. In that case you can programmatically add views to a ViewGroup with the add function. But you can't give it a name. You could give it an id, but that's not recommended. And it shouldn't really be necessary- since you created it, you shouldn't need to look it up in the view hierarchy again, which is the major reason to give a name to it.

答案2

得分: 0

是的,这是可行的。

如果您想显示一个具有动态大小的列表,可以使用RecyclerView来实现。

如果您不想显示列表,可以使用ViewGroup的addView()方法,或者使用WindowManager来动态添加视图。

val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
windowManager.addView(yourView, layoutParamsForThisView)
英文:

Yes, it's doable.

If you want to display a list with dynamic size, you can use RecyclerView to implement.

If you don't want to display a list, you can use addView() method of ViewGroup, or use WindowManager to add view dynamically.

val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
windowManager.addView(yourView, layoutParamsForThisView)

huangapple
  • 本文由 发表于 2023年5月15日 10:29:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76250535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定