我还需要用 onCreate() 声明按钮还是 "setid" 就足够了?

Do I need to declare buttons with onCreate() aswell or "setid" is enough?

我发现 this answer from @anthonycr 并且缺乏评论所需的声誉。但是,我需要一些说明。

我是否需要在 onCreate 方法中额外声明按钮,或者例如 m1.setid 就足够了?如果我有太多按钮(50),我怎么能不写 50 行 Button btn = (Button) findviewbyId(R.id.x)?

就声明它

在下面找到我关于 OnTouchListener 的代码。但是,我需要用 findviewbyId 声明我的按钮吗?如果是这样,我如何在不写 50 行 findviewbyId

的情况下声明 50 个按钮
void intialization(){
     Button m1, m2, m3, m4;
     ... //do initialization stuff
     m1.setId(1);
     m2.setId(2);
     m3.setId(3);
     m4.setId(4);
     MyTouchListener touchListener = new MyTouchListener();
     m1.setOnTouchListener(touchListener);
     m2.setOnTouchListener(touchListener);
     m3.setOnTouchListener(touchListener);
     m4.setOnTouchListener(touchListener);
 }

    
public class MyTouchListener implements OnTouchListener {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(v.getId()){
            case 1:
                //do stuff for button 1
                break;
            case 2:
                //do stuff for button 2
                break;
            case 3:
                //do stuff for button 3
                break;
            case 4:
                //do stuff for button 4
                break;
        }
        return true;
    }

}```

将它们存储在 array:

Button[] buttons = new Button[50];
for (int i=0;i<50;i++)
{
   //I imagine this is a constructor that sets the given number into the button id.
   buttons[i]=new Button(i); 
   //but you can also set it after creating it (just choose one option)
   buttons[i].setId(i);
}

之后,调用一个按钮应该是:

/*I'm guessing "1" will be the input to choose the first one.
 As arrays start at 0, I decrement the id by 1.*/

Button choosenOne = buttons[v.getId()-1];

//and now do whatever with the selected button
choosenOne.doStuff();