【问题标题】:How to include methods in every class in JAVA, like the include function in php?如何在 JAVA 中的每个类中包含方法,例如 php 中的 include 函数?
【发布时间】:2013-02-14 08:41:39
【问题描述】:

我想知道是否有一种方法可以在每个 JAVA 类中包含重复方法..

这是场景:

我有 5 种布局: 主要的.xml 布局1.xml 布局2.xml 布局3.xml 布局4.xml

我知道在 android 中您需要为每个布局设置一个类。 所以我有 5 个不同的课程。

但在所有布局中,有 4 个单选按钮使用以下代码:

public void layout1(View target) {
        // Do stuff
        Intent n1 = new Intent(main.this, layout1.class);
        startActivity(n1);
    }


    public void layout2(View target) {
        Intent n2 = new Intent(main.this, layout2.class);
        startActivity(n2);
    }

    public void layout3(View target) {
        Intent n3 = new Intent(main.this, layout3.class);
        startActivity(n3);
    }

    public void layout4(View target) {
        Intent n4 = new Intent(main.this, layout4.class);
        startActivity(n4);
    }

通过使用布局中的“android:onclick”来分配按钮。如何在每个类中包含这些方法,以便在我有很多类/布局时不需要复制和粘贴?

因为在 PHP 中,您可以使用

在每个页面中包含函数
include 'functionfilename.php';

如何在 Java 中做到这一点?有什么办法吗?

【问题讨论】:

  • 阅读继承,然后设计一个基类并扩展它

标签: android button methods onclick


【解决方案1】:

创建一个扩展 Activity 类的抽象类,将其命名为 BaseActivity,然后在您的所有活动中扩展您的 BaseActivity 类,而不是直接扩展 Activity,

【讨论】:

  • 谢谢!读完抽象类后,我能做到!
【解决方案2】:

在尝试使用 Android 进行任何操作之前,您应该学习面向对象的技术以及如何在 Java 中应用它。

【讨论】:

    猜你喜欢
    • 2014-01-07
    • 2016-03-08
    • 2018-01-06
    • 2012-02-15
    • 1970-01-01
    • 2013-11-16
    • 2011-05-01
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多