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

2023-09-03 22:02:40 作者:此去经年_

假设我们有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.