Show random string

前端 未结 3 998
我在风中等你
我在风中等你 2021-01-03 10:43

i am trying to display a random string each time a button is pressed from a set of strings defined in strings.xml . this is an example of the strings ID\'s

&         


        
3条回答
  •  猫巷女王i
    2021-01-03 10:45

    You can define your strings in an array which will help simplify this task (res/values/array.xml):

     
        string 1 
        string 2 
        string 3 
        string 4 
        string 5
     
    

    You can then create an array to hold the strings and select a random string from the array to use:

    private String[] myString; 
    
    myString = res.getStringArray(R.array.myArray); 
    
    String q = myString[rgenerator.nextInt(myString.length)];
    

    Example code:

    package com.test.test200;
    
    import java.util.Random;
    
    import android.app.Activity;
    import android.content.res.Resources;
    import android.os.Bundle;
    import android.widget.TextView;
    
    public class Test extends Activity {
    /** Called when the activity is first created. */
    
        private String[] myString;
        private static final Random rgenerator = new Random();
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
    
        Resources res = getResources();
    
        myString = res.getStringArray(R.array.myArray); 
    
        String q = myString[rgenerator.nextInt(myString.length)];
    
        TextView tv = (TextView) findViewById(R.id.text1);
        tv.setText(q);
    }
    }
    

提交回复
热议问题