Android注释自定义视图

时间:2014-03-08 10:48:22

标签: java android annotations android-annotations

我正在尝试将Android Annotations应用到我的View中。但我无法弄清楚如何正确地做到这一点。我的问题是,View中的字段始终为NULL。

我认为我对如何使用Android注释与视图和适配器有一些理解问题。有人能给我一个提示,我会如何正确地做到这一点?

在我的片段中,我使用以下适配器:

ItemAdapter

@EBean
public class ItemAdapter extends BaseAdapter {

public ItemAdapter(Context context) {
    this.context = context;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    GalleryListView view;
    if (convertView == null) {
        view = GalleryListView_.build(context);
    } else {
        view = (GalleryListView) convertView;
    }

    imageUrls = getDocumentListAll();
    DDocuments doc = documentProxy.getElementByDocument(imageUrls.get(position));
    view.init(imageUrls.get(position), Uri.fromFile(new File(doc.getPath())));

    // before I used annotations I did set my Image using this. But now I dont really know how to use this line
    // ImageLoader.getInstance().displayImage(Uri.fromFile(new File(doc.getPath())).toString(), holder.image, options, animateFirstListener);
}
}

GalleryListView

@EViewGroup(R.layout.gallery_list)
public class GalleryListView extends LinearLayout {
    @ViewById
    ImageView   image;

    @ViewById
    TextView    text;

    public void init(String imageText, Uri imageUri) {
        text.setText(imageText);
        image.setImageURI(imageUri);
    }
}

2 个答案:

答案 0 :(得分:1)

问题是当你打电话给init时没有注入Views。因此,解决方案应该是不直接设置视图的文本;相反,您希望设置一个您知道在注入后将被读入视图的变量。

实现此目的的一种方法是使用@AfterViews。在View注入发生后,将调用带有@AfterViews注释的方法。

我的头顶看起来像这样:

@EViewGroup(R.layout.gallery_list)
public class GalleryListView extends LinearLayout {
    String mText;
    Uri mUri;

    @ViewById
    ImageView   image;

    @ViewById
    TextView    text;

    public void init(String imageText, Uri imageUri) {
        mText = imageText;
        mUri = imageUri;
    }

    @AfterViews
    void afterViews() {
        text.setText(mText);
        image.setImageURI(mUri);
    }
}

这可能不是最佳解决方案,但它应该完成工作。我建议保持Android Annotation Cookbook方便;还有其他类似的注释会派上用场。

答案 1 :(得分:0)

你从哪里获取上下文?

尝试替换

    view = GalleryListView_.build(context);

    view = new GalleryListView_(context);

在任何情况下,对于如此小的视图我都没有看到使用Android Annotations的好处,也许如果你有多个我理解的资源,但对于这样的小代码,我建议你实现te构造函数并膨胀在那里资源。