Android活动作为内部类 [英] Android activity as inner class

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

问题描述

我正在尝试将Android Activity 声明为内部类.此 Activity 仅应由包含的类产生,并且需要访问其某些私有方法(我真的不想公开的方法).当尝试生成它时,我得到了:

I'm trying to declare an Android Activity as an inner class. This Activity should only be spawned by the containing class and needs access to some of its private methods (Methods I really don't want to make public.). When trying to spawn it though, I get this:

java.lang.InstantiationException: can't instantiate class com.foo.bar.baz$MyActivity; no empty constructor

该活动已在我的清单中正确声明.难道这在Android中是不可能的吗?

The activity is properly declared in my manifest. Is this just not possible in Android?

编辑:一些代码

...
public class MyActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        // Do stuff that uses the parent class's functions
        ...
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (!forwardResultToParent(requestCode, resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
        } else {
            finish();
        }
    }
}

推荐答案

内部类的实例具有对包含类的包含实例的引用.您只能通过包含类的方法(或构造函数)创建内部类的实例.

An instance of the inner class has a reference to the containing instance of the containing class. You can create an instance of the inner class only from a method (or constructor) of the containing class.

可能可以将内部类设为静态.仅在您提供显式引用的情况下,它才能访问父类字段,但我认为您可以接受.

Probably you can make the inner class static. It will be able to access the parent class fields only if you provide an explicit reference, but I think you can live with that.

您还应该考虑创建特殊的程序包并使用程序包可见性.

You should also consider creating a special package and using package visibility.

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

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