Android中的课程与活动 [英] Classes vs Activities in Android

查看:64
本文介绍了Android中的课程与活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android开发的初学者,但编程本身不是。无论如何,这个问题可能有点愚蠢。

I'm a beginner in Android development but not in programming itself. Anyway, this question might be a bit dumb.

问题是:Android活动中的所有类都与UI元素相关吗?我想拥有一个常规 Java类,我通常可以从中创建对象,而且我不知道如何定义它以及如何调用它。

The question is: Are all classes in Android activities related to a UI element? I want to have a "regular" Java class from which i can normally create objects and i'm not figuring out how to "define it" and how to "call" it.

任何帮助将不胜感激。谢谢

Any help would be much appreciated. Thanks

推荐答案

是的,您可以拥有常规的类,不,它们并不都与UI元素相关。这很像普通的Java。因此,在Eclipse中,您可以像图中一样创建一个新类,并按照一页向导进行操作。

Yes you can have regular classes and no they are not all related to a UI element. This works pretty much like normal Java. So in Eclipse you can create a new class like in the image and follow the one page wizard.

您最终将获得类似于以下的代码(我为例如):

You will end up with some code like the below (I added a few bits for the example):

package this.is.your.package;

public class Person{

    private int age;

    public void setAge(int _age)
    {
        age = _age;
    }

}

然后您可以构建方法和其他东西正常。至于实例化或访问您的课程,您可能必须将其公开以使活动获得它。但是,有许多不同的方法可以执行此操作,但是对于上面的示例,我可以这样做。

You can then build methods and other stuff as normal. As for instantiating or accessing your class you will probably have to make it public for the activities to get it. However there are a many number of different ways of doing this but for the example above I could do.

public class MyActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Person me = new Person();
        me.setAge(22); //feels old
    }

您可以看到这很正常。

这篇关于Android中的课程与活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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