使用java包含在android中

发布于 2024-10-06 23:36:31 字数 154 浏览 0 评论 0原文

我有一个包含 4 个按钮的标题视图。当我单击这 4 个按钮中的每一个时,它应该启动四个不同的活动。我还希望这些按钮出现在我的应用程序的每个视图中。

我可以使用 include 标签包含此标题视图。但是我怎样才能在每个活动中包含java代码(按钮点击等)呢?

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

叶落知秋 2024-10-13 23:36:32

创建一个单独的类,它将获取按钮作为参数,并创建和设置适当的 onClick 侦听器。然后只需从您需要的地方调用班级即可。像这样:

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
   }

在您的活动中:

new ButtonInitializer(btn1, btn2, btn3, btn4).init();

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文