Include in android using java

2019-05-18 12:51发布

I have a header view which contains 4 buttons. When I click each of these 4 buttons it should start four different activities. And also I want these buttons in every view of my application.

I can include this header view using include tag. But how can I include the java code (button click etc) in every activities?

Thank you

1条回答
不美不萌又怎样
2楼-- · 2019-05-18 13:03

Make a separate class which will get the buttons as parameters and which will create and set the appropriate onClick listeners. Then just call the class from where you need. Like this:

public class ButtonInitializer {

  private Button btn1, btn2, btn3, btn4;

  public ButtonInitializer(Button btn1, Button btn2/* and another 2 here*/) {
     this.btn1 = btn1;
     this.btn2 = btn2;
     this.btn3 = btn3;
     this.btn4 = btn4;
  }

  public void init() {
     btn1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick() {
           // your code
        }
     }
     // and for other buttons
   }

in your activity:

new ButtonInitializer(btn1, btn2, btn3, btn4).init();
查看更多
登录 后发表回答