Show random string

前端 未结 3 990
我在风中等你
我在风中等你 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条回答
  • 2021-01-03 10:45

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

    <string-array name="myArray"> 
        <item>string 1</item> 
        <item>string 2</item> 
        <item>string 3</item> 
        <item>string 4</item> 
        <item>string 5</item>
    </string-array> 
    

    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);
    }
    }
    
    0 讨论(0)
  • 2021-01-03 10:50

    create string array in res/values/array.xml:

    <?xml version="1.0" encoding="utf-8"?>  
        <resources>  
    <string-array name="custom_array"> 
        <item>aalia</item> 
        <item>asin</item> 
        <item>sonakshi</item> 
        <item>kajol</item> 
        <item>madhuri</item>
    </string-array> 
    </resources>
    

    then in your activity write the code

    String[] array = context.getResources().getStringArray(R.array.custom_array);
    
            String randomStr = array[new Random().nextInt(array.length)];
    
            text_dialog.setText(""+randomStr);
    
    0 讨论(0)
  • 2021-01-03 11:08

    Why do you need this?

    R.string.q0

    Assuming getString(RandomQ) is a valid statement, I would think

    int RandomQ = rgenerator.nextInt(5) + 1;
    

    would work just fine.

    Also, as a side note: A lot of times those autofixes in your IDE are unreliable and unsafe to use. Unless you know why it's telling you to do something, don't do it.

    0 讨论(0)
提交回复
热议问题