【问题标题】:how to select a string randomly in Android? [duplicate]如何在Android中随机选择一个字符串? [复制]
【发布时间】:2014-10-24 02:56:34
【问题描述】:

我正在使用一个测验应用程序,因此每次活动启动文本视图时,它应该是从字符串中随机选择的不同问题 我现在所做的是: 我在活动中有文本视图,并且值中有某些字符串。每次启动活动时,我应该怎么做才能显示不同的字符串。谁能帮我?

【问题讨论】:

  • 你尝试了什么?
  • 将字符串放入一个数组中,然后生成一个随机索引。
  • 随机 r = new Random(); int randomNo = r.nextInt(字符串数组长度);

标签: java android string


【解决方案1】:
    static final String AB = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    static Random rnd = new Random();

    String randomString( int len ) 
    {
       StringBuilder sb = new StringBuilder( len );
       for( int i = 0; i < len; i++ ) 
          sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
       return sb.toString();
    }
String random_st=randomString(10)

【讨论】:

    【解决方案2】:

    创建一个包含字符串资源的所有 id 的数组,并在每次活动开始时选择一个随机数。 比如:

    int arr[] = new int[]{R.string.str1, R.string.str2};
    @override 
    public void onCreate(Bundle data) {
        Random r = new Random(arr.length);
        //TextView.setText(getResources().getString(arr[r.nextInt()]);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-13
      • 2012-02-03
      相关资源
      最近更新 更多