我目前正在使用的是下面的代码,但这是在开始时生成一个随机数(定义为d20),然后只要我点击按钮就调用该数字。如何更改此选项以便在单击按钮时生成该代码(rndNumbers.nextInt(20)+1)。
我意识到其他人已经提出了类似的问题,但我没有看到它与我的完全一样(我几乎是一个初学者,所以我不太了解其他人的代码)。
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Random rndNumbers = new Random();
int d20 = rndNumbers.nextInt(20) +1;
Button roll;
TextView display;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
roll = (Button) findViewById(R.id.bRoll);
display = (TextView) findViewById(R.id.tvDisplay);
roll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
display.setText("The dice lands on " + d20);
}
});
};
@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;
}
}
答案 0 :(得分:0)
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Random rndNumbers = new Random();
int d20 = rndNumbers.nextInt(20) +1;
Button roll;
TextView display;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
roll = (Button) findViewById(R.id.bRoll);
display = (TextView) findViewById(R.id.tvDisplay);
roll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
d20 = rndNumbers.nextInt(20) +1;
display.setText("The dice lands on " + d20);
}
});
};
@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;
}
}