根据随机值获取数组元素

Obtaining an array element based on a random value

假设我们有一个包含 100 个字符串的数组,您可以从 R.string.xml.

中获取它们
private String lapi[]={"R.string.lapi0", "R.string.lapi1", "R.string.lapi2", "R.string.lapi3"..."R.string.lapi99};

我们还有一个 TextView 和一个 Button:

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

我们希望当我们点击按钮时得到一个 0 到 100 之间的随机值:

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

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

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

这是我认为最有效的解决方案,但行不通。

你知道是否还有其他类似的工作方式,无需使用开关。

对不起,如果我的英语不清楚。

提前致谢!

getString() 需要资源 ID,你只是给了一个字符串(即使它 "corresponds" 到相同的文本 ID,它也只是一个字符串)。

你想要实现的可以使用 getIdentifier() 完成(你甚至不需要数组):

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

请注意,使用 id 检索资源效率更高,如文档所述:

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