簡體   English   中英

生成隨機數會停止應用程序

[英]Generating random number stops application

我試圖在單擊Button時生成一個隨機數,並在EditText打印該值

我用這個代碼制作了它

public class Board_Play1 extends Activity {

int d;
Random random = new Random();
@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.board_play1);

    Button button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            d=random.nextInt(6)+1;
            EditText diceno = (EditText) findViewById(R.id.editText1);
            diceno.setText(d);

        }
    }); 

}

但是在單擊按鈕后運行應用程序時會彈出錯誤,說Unfortunately, your app has stopped 不明白為什么會這樣。 任何人都能解釋錯誤是什么嗎?

您需要調用接受CharSequence作為參數的setText方法。

目前你正在調用setText(int resid) ,它將嘗試找到指定了id的正確資源,所以我猜你的程序正在拋出ResourceNotFoundException

所以:

diceno.setText(String.valueOf(d));

這會將你的int轉換為String

同時移動EditText diceno = (EditText) findViewById(R.id.editText1); onClick方法之前。 沒有必要在每個onClick事件上檢索它,只需一次就足夠了。

最后,不要忘記用你的問題發布stacktrace。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM