搜尋

首頁  >  問答  >  主體

android - AS中Module中没法使用Butterknife.有什么好的替代?

说是Module中的R文件下的id不是final的。然后Butterknife就不行。。。
估计别的注解类型的也不好使吧。。。于是乎有什么办法么。。

详见:https://github.com/JakeWharton/butterknife/issues/100

以下是作者JakeWharton在14年12月的原话。。。

Yes this is not supported. This is a tradeoff between ease-of-use and what I tolerate as a sane API.

The only way to accomplish something like this is to allow string values like this:

@InjectView(name = "content_frame") protected FrameLayout
contentFrame; The downside's to this are:

The downside's to this are:

  • It's not rename-safe or compile-safe (kind of). If you open the layout XML for this and do an IDE-backed rename operation it will not catch this string and update it. It also means you can (technically) compile the above code if there is no content_frame ID that exists. Now the compilation will eventually fail because the generated code will become invalid.

  • It's hard to know what R class to reference in the generated code, especially when you take into consideration the fact that you can use references to IDs that exist in libraries that you are referencing.

  • It forces us to have defaults for both the value and name properties on each annotation which means you can write @InjectView Foo foo and Butter Knife will have to fail the builder rather than javac.

Because of these facts, I have chosen not to support library projects.

One way that this could potentially be solved is to use a Gradle plugin rather than an annotation processor. I don't have the time to explore something like that for a few months though.

天蓬老师天蓬老师2772 天前593

全部回覆(7)我來回復

  • 阿神

    阿神2017-04-17 17:33:58

    Android Studio Prettify

    這個外掛自動產生findViewById等內容,你可以試試看。
    你說Butterknife不能用,應該是你用錯了吧,你仔細看看是不是用錯了。

    回覆
    0
  • 怪我咯

    怪我咯2017-04-17 17:33:58

    module好像也沒看到別的,還是直接用findViewById吧

    回覆
    0
  • ringa_lee

    ringa_lee2017-04-17 17:33:58

    現在基本上不用butterknife了,直接封裝一個方法在BaseActivity或BaseFragment

    //BaseActivity
    public <T extends View> T $(@IdRes int resId){
        return (T)super.findViewById(resId);
    }
    //BaseFragment
    public <T extends View> T $(View layoutView, @IdRes int resId){
        return (T)layoutView.findViewById(resId);
    }
    //使用
    TextView tvName=$(R.id.tv_name);

    回覆
    0
  • PHP中文网

    PHP中文网2017-04-17 17:33:58

    這個也行,功能比較多
    https://github.com/excilys/androidannotations

    回覆
    0
  • 迷茫

    迷茫2017-04-17 17:33:58

    最好使用系統自帶的findviewyid來找出id,第三方的工具之間使用會存在衝突

    回覆
    0
  • PHPz

    PHPz2017-04-17 17:33:58

    RoboGuice?或android annotation?

    回覆
    0
  • 黄舟

    黄舟2017-04-17 17:33:58

    回覆
    0
  • 取消回覆