【问题标题】:roboguice inject in customerroboguice 注入客户
【发布时间】:2013-12-12 11:47:06
【问题描述】:

我有一个小部件视图如下:
public class RemoteNumView extends FrameLayout {
我如何像在 RoboActivity 中一样使用 Roboguice?如下:

 @InjectView(R.id.btn_remote_control_num_0)
private TextView mText;

完整代码为:

/**
* Created by bbcv on 13-12-12.
*/

public class RemoteNumView extends FrameLayout {
private IService mService;

@InjectView(R.id.btn_remote_control_num_0)
private TextView mText;

public RemoteNumView(Context context) {
    super(context);
    ///
    addView(LayoutInflater.from(context).inflate(R.layout.v_remote_control_fun,null));
}

public RemoteNumView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public RemoteNumView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public void setService(IService service){
    mService = service;
}
}

有人可以帮忙吗?

【问题讨论】:

    标签: android view inject roboguice


    【解决方案1】:

    通过编写自定义代码解决了这个问题。 Roboguice 写得很糟糕。

     protected void injectViews() {
        for (Field field : this.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(InjectView.class)) {
                if (Modifier.isStatic(field.getModifiers())) {
                    throw new UnsupportedOperationException("Views can't be staticaly assigned.");
                } else {
                    if (View.class.isAssignableFrom(field.getType())) {
                        try {
                            final InjectView injectView = field.getAnnotation(InjectView.class);
                            ;
                            final int id = injectView.value();
                            View view = findViewById(id);
                            if ((view == null) && Nullable.notNullable(field)) {
                                throw new NullPointerException(String.format("Can't inject null value into %s.%s when field is not @Nullable", field.getDeclaringClass(), field.getName()));
                            }
                            field.setAccessible(true);
                            field.set(this, view);
                        } catch (IllegalAccessException e) {
                            throw new IllegalStateException(e);
                        }
                    } else {
                        throw new UnsupportedOperationException("Need view type to assign");
                    }
                }
            }
        }
    

    【讨论】:

    • 最终使用 ButterKnife 作为更好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    相关资源
    最近更新 更多