android - AS中Module中没法使用Butterknife.有什么好的替代?
天蓬老师
天蓬老师 2017-04-17 17:31:58
0
7
587

说是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.

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(7)
阿神

Android Studio Prettify

This plug-in automatically generates findViewById and other content, you can try it.
You said Butterknife can’t be used. It’s probably because you’re using it wrong. Check carefully to see if you’re using it wrong.

刘奇

I don’t seem to see anything else in the module, so just use findViewById directly

左手右手慢动作

Nowadays, butterknife is basically no longer needed, and a method is directly encapsulated in BaseActivity or 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);
洪涛

This one works too, it has more functions
https://github.com/excilys/androidannotations

迷茫

It is best to use the findviewyid that comes with the system to find the ID. There will be conflicts between third-party tools

PHPzhong

RoboGuice? or android annotation?

黄舟

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template