如何从文本列表中显示随机文本?

时间:2014-04-11 17:08:37

标签: android

我正在创建一个应用程序,它将显示预先确定的文本列表中的随机文本。首先,我将如何创建预定文本列表?我会列一个清单吗?如果是这样解释。其次,我希望我的应用程序中的按钮选择其中一个文本随机显示。我该怎么做呢?

    package com.Steed.namemeaning;
    import android.R.string;
    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;





     public class MainActivity extends Activity {
TextView meaning;
Button press;
EditText et1;
String[] nm;

      @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    press = (Button)findViewById (R.id.b1);
    meaning = (TextView)findViewById(R.id.tv1);
    et1 = (EditText)findViewById(R.id.et1);


    nm = new String[7];
    nm[0] = "your name means0";
    nm[1] = "your name means1";    
    nm[2] = "your name means2";
    nm[3] = "your name means3";
    nm[4] = "your name means4";
    nm[5] = "your name means5";
    nm[6] = "your name means6";
    nm[7] = "your name means7";






    press.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            int x = 0 + (int)(Math.random() * ((7 - 0) + 1));
            String list = nm[x];
            meaning.setText(list);

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

1 个答案:

答案 0 :(得分:0)

这里有ArrayIndexOutOfBoundsException由于尝试将值放入具有7个元素的字符串数组的第8个元素而导致。快速解决方法是:

nm = new String[8];