android-如何创建可重用功能? [英] android - how to create a reusable function?

查看:78
本文介绍了android-如何创建可重用功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的android项目中,我有很多活动,其中一些活动已经扩展了诸如地图活动或BroadcastReceiver之类的其他内容.

In my android project, I have many activities and some of them already extend other stuff like map activity or BroadcastReceiver.

我如何创建可以从任何活动中调用的函数,因为我不想在多个活动中重复任何代码.

How do I create a function that I can call from any activity, because I don't want to have to repeat any code in multiple activities.

谢谢.

推荐答案

如果我具有有用的功能,可以执行一些我想从多个Activity中调用的有用的任务,则可以创建一个名为Util的类,并将其停放在其中.我将它们设置为 static ,因此无需分配任何对象.

If I have useful functions that perform little helpful tasks that I want to invoke from several Activities, I create a class called Util and park them in there. I make them static so that I don't need to allocate any objects.

以下是我编写的此类课程的一部分的示例:

Here is an example of part of one such class I wrote:

public final class Util {
    public final static int KIBI = 1024;
    public final static int BYTE = 1;
    public final static int KIBIBYTE = KIBI * BYTE;

    /**
     * Private constructor to prevent instantiation
     */
    private Util() {}

    public static String getTimeStampNow() {
        Time time = new Time();
        time.setToNow();
        return time.format3339(false);
    }
}

要使用这些常量和方法,我可以从类名称而不是任何对象中访问它们:

To use these constants and methods, I can access them from the class name, rather than any object:

int fileSize = 10 * Util.KIBIBYTE;
String timestamp = Util.getTimeStampNow();

除了这堂课之外,全班还有很多,但您明白了.

There's more to the class than this, but you get the idea.

这篇关于android-如何创建可重用功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆