【问题标题】:Connecting ButtonArray to XML buttons将 ButtonArray 连接到 XML 按钮
【发布时间】:2016-01-09 09:03:36
【问题描述】:

首先感谢您的帮助。 我正在创建一个计算器应用程序, 在 XML 文件中,我创建了按钮 [0-9] 现在我想把它们都放在按钮数组中

 int NumberOfButtons=10;

Button button[] = new Button[NumberOfButtons];

这是数组, 在尝试使用数组之前,我创建了每个按钮

 Button one, two, three, four, five, six, seven, eight, nine, zero, add, sub, mul, div, cancel,
        equal;

现在这是通过 findValueid 连接的按钮

 one = (Button) findViewById(R.id.button1);
    two = (Button) findViewById(R.id.button2);
    three = (Button) findViewById(R.id.button3);
    four = (Button) findViewById(R.id.button4);
    five = (Button) findViewById(R.id.button5);
    six = (Button) findViewById(R.id.button6);
    seven = (Button) findViewById(R.id.button7);
    eight = (Button) findViewById(R.id.button8);
    nine = (Button) findViewById(R.id.button9);
    zero = (Button) findViewById(R.id.button0);

如何节省处理能力并使用更少的代码? 像 FOR 函数 或者也许使用 While

谢谢大家!

【问题讨论】:

    标签: java android arrays button android-studio


    【解决方案1】:

    您可以使用GridView 来制作。这样代码更少,可读性更高。

    【讨论】:

    • 任务需要按钮 :(
    • 我知道。每个 gridView 的项目都是一个按钮,如 button1、button2...等。
    【解决方案2】:

    您的代码已经非常简单并且可以快速执行。通常,每个按钮都需要像您一样编写 - 这使得计算器编写代码很痛苦。在这种情况下,我认为循环的使用不适用——不是为了提高效率。

    现在您需要确定 onTouch() 事件的位置,以便为您的按钮放置和检测触摸事件。

    @FireSun 的建议很有帮助。

    【讨论】:

      【解决方案3】:

      试试这个。

      int[] ids = {
          R.id.button1
          , R.id.button2
          , R.id.button3
          ...
          , R.id.button9
      }
      
      for (int id : ids) {
          findViewById(id).setOnClickListener(this);
      }
      

      如果你的按钮 id 有规则,试试这个。

      for (int i = 0; i < numberOfButtons; i++) {
          String buttonId = "button" + i;
          int resourceId = getResources().getIdentifier(buttonId, "id", getPackageName());
          findViewById(resourceId).setOnClickListener(this);
      }
      

      【讨论】:

        猜你喜欢
        • 2014-08-29
        • 1970-01-01
        • 1970-01-01
        • 2012-05-05
        • 2012-12-06
        • 2015-12-01
        • 1970-01-01
        • 2023-03-30
        • 2019-12-03
        相关资源
        最近更新 更多