Randomize string from resources android

2019-02-28 04:53发布

问题:

I have tried this:

   int[] trivias = {
        R.string.trivia1, R.string.trivia2, R.string.trivia3, R.string.trivia4, R.string.trivia5,
        R.string.trivia6, R.string.trivia7, R.string.trivia8, R.string.trivia9, R.string.trivia10,
        R.string.trivia11, R.string.trivia12, R.string.trivia13, R.string.trivia14, R.string.trivia15,
        R.string.trivia16, R.string.trivia17, R.string.trivia18, R.string.trivia19, R.string.trivia20,
        R.string.trivia21, R.string.trivia22, R.string.trivia23, R.string.trivia24, R.string.trivia25,
        R.string.trivia26, R.string.trivia27, R.string.trivia28, R.string.trivia29, R.string.trivia30,
        R.string.trivia31, R.string.trivia32, R.string.trivia33, R.string.trivia34, R.string.trivia35,
        R.string.trivia36, R.string.trivia37, R.string.trivia38, R.string.trivia39, R.string.trivia40,
        R.string.trivia41, R.string.trivia42, R.string.trivia43, R.string.trivia44, R.string.trivia45,
        R.string.trivia46, R.string.trivia47, R.string.trivia48, R.string.trivia49, R.string.trivia50,
};

TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.trivias);

    tv = (TextView) findViewById (R.id.tvTrivias);

    Random ran = new Random();


    tv.setText(ran.nextInt(trivias.length));



}

But logcat gives me ResourcesNotFound exception. What am I missing here? Thanks.

回答1:

this.. may be..

tv.setText(trivias[ran.nextInt(trivias.length)]);

What you are doing right now is searching for resource with id, thats generated by ran.nextInt()



回答2:

You are not pass int trivias:-

tv.setText(trivias[ran.nextInt(trivias.length)]);

You just forgot to trivias[]