【问题标题】:Do I need to declare buttons with onCreate() aswell or "setid" is enough?我是否还需要使用 onCreate() 声明按钮或“setid”就足够了?
【发布时间】:2020-10-27 04:02:30
【问题描述】:

我找到了this answer from @anthonycr,但缺乏评论所需的声誉。不过,我可以澄清一下。

我是否需要在onCreate 方法或例如m1.setid 中添加额外的声明按钮就足够了?如果我的按钮太多(50 个),如何在不写 50 行 Button btn = (Button) findviewbyId(R.id.x) 的情况下声明它?

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

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

}```

【问题讨论】:

  • 添加了原始答案的链接,改进了语法。

标签: java android android-studio button event-handling


【解决方案1】:

将它们存储在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();

【讨论】:

  • 看看更灵活的规范,如 ArrayList、HashMaps 等。数组是基本的,有时你需要更多的东西。不客气
  • 对 sur 来说是的,我知道并且我可以使用数组、for 循环、类、继承、实现、多态性。但正如您所知,当需要将所有东西连接在一起时,需要多年的经验。
  • 你是在正确的方式,不要担心你需要多少。罗马一点一点地完成了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 2014-12-07
  • 1970-01-01
相关资源
最近更新 更多