我是否需要使用 onCreate() 声明按钮,或者"setid"就足够了?



我从@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();

相关内容

最新更新