2017-03-16 113 views
-5

我有十個按鈕,如計算器顯示從0到9.問題是我想每次按下按鈕時每個按鈕上顯示唯一的隨機數。如何可能?在android中的按鈕上顯示不同的隨機數

我的代碼是:

public void generate(View view){ 
    Random rand=new Random(); 
    int number=rand.nextInt(10); 


    but2=(Button)findViewById(R.id.button5); 

    but3=(Button)findViewById(R.id.button6); 
    but4=(Button)findViewById(R.id.button7); 
    but5=(Button)findViewById(R.id.button8); 
    but6=(Button)findViewById(R.id.button9); 
    but7=(Button)findViewById(R.id.button10); 
    but8=(Button)findViewById(R.id.button11); 
    but9=(Button)findViewById(R.id.button12); 
    but0=(Button)findViewById(R.id.button13); 
    but1=(Button)findViewById(R.id.button); 
    String mynumber=String.valueOf(number); 

    but2.setText(a); 

    but3.setText(mynumber); 
    but4.setText(mynumber); 
    but5.setText(mynumber); 
    but6.setText(mynumber); 
    but7.setText(mynumber); 
    but8.setText(mynumber); 
    but9.setText(mynumber); 
    but0.setText(mynumber); 
    but1.setText(mynumber); 
    but2.setText(mynumber); 
+0

能告訴你使用一些代碼,您已經有了?你是如何定義按鈕的,你在使用ButterKnife嗎? – Murf

+0

我沒有使用butterknife – bini

+2

用0到9的數字填充一個列表,隨機和迭代。 – QBrute

回答

-3

檢查完成answer

int randomWithRange(int min, int max){ 
    int range = (max - min) + 1;  
    return (int)(Math.random() * range) + min; 
} 
+0

請將完整答案作爲答案。而這又如何保證唯一性? – Bathsheba

-2

是的,這是可能的。

如何

  • 找到你的按鈕。事件:onCreate
  • 將onClickListener事件添加到您的按鈕。

例子:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    this.button_component = (Button) findViewById(R.id.button_component); 
    this.button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      // RANDOM YOUR NUMBER.    
     } 
    }); 
} 
相關問題