1

对于那些在 android 编码领域待了很长时间的人来说,这是一个简单的问题!我做过研究,关于这个问题的研究。试过了,但是运行应用程序时总是出错。

问题是,我如何制作一个按钮,在 textview 上显示 1 到 100 之间的随机数?

4

2 回答 2

8
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));
    }    
});
于 2012-05-02T23:43:19.630 回答
2

这是一些可能有帮助的示例代码。

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));
            }
        });
    }
}
于 2012-05-03T00:08:33.440 回答