我试图从一堆XML <string-array>
资源中获取一个随机字符串,我为此创建了一个函数:
public class RandomFunction {
String[] catagories= {"marriage","life"};
public String getRandom(Activity activity) {
int index = new Random().nextInt(catagories.length);
String cat = catagories[index];
String[] data = activity.getResources().getStringArray(R.array.**cat**);
index = new Random().nextInt(data.length);
cat = data[index];
return cat;
}
}
我正在做的是接下来R.array.
并附加字符串 cat ,但它无效。我怎么能这样做?
答案 0 :(得分:0)
试试这个:
public class RandomFunction {
Context context;
public RandomFunction(Context context) {
this.context = context;
}
public String generate() {
String[] albums = context.getResources().getStringArray(R.array.cat);
List<String> albumList = Arrays.asList(albums);
Random random = new Random();
int randomNo = random.nextInt(albumList.size());
return albumList.get(randomNo);
}
}
来自多个阵列:
public class RandomFunction {
Context context;
public RandomFunction(Context context) {
this.context = context;
}
public String generate() {
List < String > finalList = new ArrayList < > ();
String[] album1 = context.getResources().getStringArray(R.array.cat1);
List < String > albumList1 = Arrays.asList(albums);
String[] album2 = context.getResources().getStringArray(R.array.cat2);
List < String > albumList2 = Arrays.asList(albums);
for (int i = 0; i < albumList1.size(); i++) {
finalList.add(albumList1.get(i);
}
for (int j = 0; j < albumList2.size(); j++) {
finalList.add(albumList2.get(j);
}
Random random = new Random();
int randomNo = random.nextInt(albumList.size());
return finalList.get(randomNo);
}
}
请注意,cat数组应位于您的values文件夹::: string.xml