当我点击我的按钮时,它会显示一个随机数,但当我再次点击它时,没有任何反应。每次点击它时,如何让按钮显示一个随机数?
public class MainActivity extends ActionBarActivity {
private int randomNumber;
private Button button;
private TextView numbersDisplayed;
private int[] allNumbers;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
numbersDisplayed = (TextView)findViewById(R.id.numbersDisplayed);
allNumbers= new int[]{1,2,3,4,5,6,7,8,9};
int numArrayLength = allNumbers.length;
randomNumber = (int)(Math.random() * numArrayLength);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
numbersDisplayed.setText(String.valueOf(allNumbers[randomNumber]));
break;
}
}
});
}
}
答案 0 :(得分:4)
移动在onClick
方法中生成随机数所需的逻辑(因此每次单击按钮时都会运行):
public class MainActivity extends ActionBarActivity {
private int randomNumber;
private Button button;
private TextView numbersDisplayed;
private int[] allNumbers;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
numbersDisplayed = (TextView)findViewById(R.id.numbersDisplayed);
allNumbers= new int[]{1,2,3,4,5,6,7,8,9};
int numArrayLength = allNumbers.length;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
randomNumber = (int)(Math.random() * numArrayLength);
numbersDisplayed.setText(String.valueOf(allNumbers[randomNumber]));
break;
}
}
});
}
}