6

我在使用 AndroidAnnotations 构建活动时遇到了一些麻烦。我有一个名为 TemplateActivity 的父 Activity:

@EActivity(R.layout.activity_template)
@NoTitle
public class TemplateActivity extends Activity
{
    // some views
    // ...
    @ViewById(R.id.main_framelayout)
    FrameLayout mainFrameLayout;

    @AfterViews
    public void postInit()
    {
        Log.d("DEBUG", "postInit"); // never called, strange... 
    }

    public void setMainView(int layoutResID)
    {
        mainFrameLayout.addView(LayoutInflater.from(this).inflate(layoutResID, null));
    }
}

在我的第二个活动中,我想用另一个布局 xml 填充 mainFrameLayout:

@EActivity
public class ChildActivity extends TemplateActivity
{
    @Override
    public void postInit()
    {
        super.postInit();

        setMainView(R.layout.activity_child_one);       
    }
}

当我想启动活动时,我的 ChildActivity 是空白的,并且从未调用过 postInit。谁能告诉我有什么问题?感谢提前。

4

3 回答 3

7

The annotation in your parent class will result in a class TemplateActivity_ with the specified layout. The child class will inherit the "normal" stuff from that parent class, but have its own AA subclass (ChildActivity_). So you should specify the layout to use there as well. Just take a look at the generated classes to see what is going on there.

AA works by generating a new subclass for your annotated classes (e.g. TemplateActivity_ extends TemplateActivity) that contains the code necessary to achieve the results of your annotations. For example, in this class the onCreate() method will instantiate the layout needed, methods annotated with @Background get overridden with another implementation that calls the original method in a background thread. AndroidAnnotations doesn't really do anything at runtime, everything can be seen in the classes it generates, just look into the .apt_generated folder (or wherever you generated the classes to). This can also be helpful if it doesn't quite do what you want, because you can then just take a look at what it does and do it yourself in the way you need it.

In your case, the inheritance hierarchy is like this:

TemplateActivity (with annotations)
L--> TemplateActivity_ (with generated code for the layout)
L--> ChildActivity (your other class, no generated code)
     L--> ChildActivity_ (with code generated for the annotations in ChildActivity)

Afaik not all annotations are passed on to subclasses.

于 2013-09-02T18:40:45.570 回答
2

在子类中使用 @EActivity(R.layout.activity_child_one) 并使父类抽象。这对我有用。

于 2013-09-02T14:46:41.083 回答
0

我认为你应该让 TempleteActivity 成为一个抽象类。

于 2013-09-01T22:45:33.330 回答