【问题标题】:display different random numbers on buttons in android在android中的按钮上显示不同的随机数
【发布时间】:2017-08-07 12:41:13
【问题描述】:

我有 10 个按钮(就像计算器一样)显示从 0 到 9 的数字。

问题是我想在每次按下按钮时在每个按钮上显示唯一的随机数。我怎样才能实现这种行为?

我的代码是:

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);

【问题讨论】:

  • 你能展示使用一些你已经拥有的代码吗?你是如何定义按钮的,你用的是 ButterKnife 吗?
  • 我没有使用黄油刀
  • 用 0 到 9 的数字填充列表,随机播放和迭代。

标签: java android random


【解决方案1】:

检查完成answer

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

【讨论】:

  • 请将完整答案作为答案。这如何保证唯一性?
【解决方案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.               
        }
    });
}

【讨论】:

    猜你喜欢
    • 2021-08-02
    • 2016-08-01
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多