这对于那些在android编码场景中持续很长时间的人来说是一个简单的问题!我做过研究,研究这个问题。试过了,但是当应用程序运行时总是有错误。在文本视图上生成1到100之间的随机数的按钮
问题是,我怎么能做一个按钮,显示1到100之间的随机数在textview?
这对于那些在android编码场景中持续很长时间的人来说是一个简单的问题!我做过研究,研究这个问题。试过了,但是当应用程序运行时总是有错误。在文本视图上生成1到100之间的随机数的按钮
问题是,我怎么能做一个按钮,显示1到100之间的随机数在textview?
final Random r = new Random();
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.onClickListener(){
public void onClick(...){
textView.setText(Integer.toString(r.nextInt(100)+1));
}
});
我会把这个放在哪里?如何声明最佳按钮是否生成,最终文本显示输出? –
@Yann关注developer.android.com – Javanator
以下是一些可能有所帮助的示例代码。
public class SampleActivity extends Activity {
private TextView displayRandInt;
private Button updateRandInt;
private static final Random rand = new Random();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(/* Your Activity's XML layout id */);
/* Setup your Activity */
// Find the views (their ids should be specified in the XML layout file)
displayRandInt = (TextView) findViewById(R.id.displayRandInt);
updateRandInt = (Button) findViewById(R.id.updateRandInt);
// Give the Button an onClickListener
updateRandInt.setOnClickListener(new View.onClickListener() {
public void onClick(View v) {
int randInt = rand.nextInt(100)+1;
displayRandInt.setText(String.valueOf(randInt));
}
});
}
}
是的,这很容易。告诉我们你到目前为止做了什么,我们会帮助你。 – SJuan76
不确定你是否是母语为英语的人,但是使用逗号稍微偏离一点:P。 –
我是法国人!对不起!我试图执行代码,但得到错误 –