Include in android using java
I have a header view which contains 4 buttons. When 开发者_StackOverflow中文版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
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();
精彩评论