获得基于随机值的数组元素

编程入门 行业动态 更新时间:2024-10-28 17:29:47
本文介绍了获得基于随机值的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我们有100个字符串,你从R.string.xml让他们的阵列。

Suppose we have an array of 100 Strings, which you get them from R.string.xml.

private String lapi[]={"R.string.lapi0", "R.string.lapi1", "R.string.lapi2", "R.string.lapi3"..."R.string.lapi99};

另外,我们有一个TextView和一个Button:

Also we have a TextView and a Button:

pelicula=(TextView)findViewById(R.id.lapicera); btnElegir=(Button)findViewById(R.id.btnElegir);

和我们想,当我们点击按钮让我们0到100之间的随机值:

and we want that when we click the button get us a random value between 0 and 100:

int random=(int) Math.round(Math.random()*100);

问题:什么是编辑的TextView使用到的随机值所属的数组值的最简单的方法? 我想要做的是这样的:

The problem: what would be the easiest way to edit the TextView with the array value to which the random value belongs ?. What I want to do is something like this:

pelicula.setText(getResources().getString(lapi[random]));

这是我认为最有效的解决方案,但不起作用。

That is the most effective solution I thought, but doesn't work.

你知道,如果有其他类似的工作,这样一来?,而不必使用一个开关。

Do you know if there are other similar work as this way ?, without having to use a switch.

很抱歉,如果我的英语不太清楚。

Sorry if my english isn't clear.

在此先感谢!

推荐答案

的getString()预计资源ID,你只是给一个String(即使它对应同一个文本的ID,它只是一个字符串)。

getString() expects the resource id, you are just giving a String (even if it "corresponds" to the same textual id, it's just a String).

您想实现是可以做到用 则getIdentifier() (你甚至不需要数组):

What you want to achieve can be done using getIdentifier() (and you don't even need the array):

Random r = new Random(); ... int randomId = r.nextInt(100); int resID = getResources().getIdentifier("lapi"+randomId, "string", getPackageName()); pelicula.setText(resID);

请注意,这是更有效的检索与ID的资源,为DOC状态:

Be aware that it's more efficient to retrieve the resource with the id, as the doc states:

注:该函数的使用是不鼓励。它是更有效   检索由标识符资源比的名字。

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

更多推荐

获得基于随机值的数组元素

本文发布于:2023-11-30 11:16:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649783.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!