使用多维数组设置随机文本

时间:2016-11-11 09:35:53

标签: java android multidimensional-array settext

我正在尝试将具有随机数的多维数组的setText设置为textView。它工作正常但只有一次。我怎样才能使每个按钮点击文本一次又一次地改变自己。这是我的代码(为了简单起见,我剪了一下):

public class MainActivity extends Activity implements View.OnClickListener{
String quiz[][];
int ques;
int ans;
Random myRand = new Random();
int myInt = myRand.nextInt(10);


 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

        quiz = new String[3][2];

    quiz[0][0] = "Q:1";
    quiz[0][1] = "A:1";

    quiz[1][0] = "Q:2";
    quiz[1][1] = "A:2";

    quiz[2][0] = "Q:3";
    quiz[2][1] = "A:3";



    ques = 0;
    ans = 1;

    button4 = (Button)findViewById(R.id.button4);
    button4.setOnClickListener(this);

    textView2 = (TextView)findViewById(R.id.textView2);
    textView3 = (TextView)findViewById(R.id.textView3);
}
    @Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.button4:
                textView2.setText(quiz[myInt][ques]);
                textView3.setText(quiz[myInt][ans]);
            break;
}
}

2 个答案:

答案 0 :(得分:1)

很简单,你应该在onClick事件

中制作新的随机数
    @Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.button4:
                myInt = myRand.nextInt(10);
                textView2.setText(quiz[myInt][ques]);
                textView3.setText(quiz[myInt][ans]);
            break;
}

答案 1 :(得分:0)

只有在实例化Activity时才生成一次随机int。您需要在按钮点击时生成它:

public void onClick(View view) {
    switch (view.getId()) {
        case R.id.button4:
                myInt = myRand.nextInt(10);
                textView2.setText(quiz[myInt][ques]);
                textView3.setText(quiz[myInt][ans]);
            break;
}