在android中的按钮上显示不同的随机数

问题描述:

我有十个按钮,如计算器显示从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

检查完成answer

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

请将完整答案作为答案。而这又如何保证唯一性? – Bathsheba

是的,这是可能的。

如何

  • 找到你的按钮。事件: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.    
     } 
    }); 
}