I'm trying to setText to a textView with multidimensional array with random number. It works fine but only once. How can i make it so that with each button click the text changes itself again and again. Here is my code (I cut it a bit to keep it simple):
我正在尝试将具有随机数的多维数组的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 个解决方案
#1
1
Its simple, you should make new random in onClick
event
它很简单,你应该在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;
}
#2
0
You generate a random int only once, when Activity is instantiated. You need to generate it on button click:
当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;
}
#1
1
Its simple, you should make new random in onClick
event
它很简单,你应该在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;
}
#2
0
You generate a random int only once, when Activity is instantiated. You need to generate it on button click:
当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;
}