用多维数组设置随机文本
Set random text with multidimensional array
我正在尝试将 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;
}
}
当 Activity 被实例化时,您只生成一次随机整数。您需要在单击按钮时生成它:
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;
}
很简单,你应该在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;
}
我正在尝试将 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;
}
}
当 Activity 被实例化时,您只生成一次随机整数。您需要在单击按钮时生成它:
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;
}
很简单,你应该在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;
}