8

Android RoboGuice开源框架、Butter Knife开源框架浅析

 3 years ago
source link: https://renyugang.blog.csdn.net/article/details/37814665
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Android RoboGuice开源框架、Butter Knife开源框架浅析

Google Guice on Android(RoboGuice)

今天介绍一下Google的这个开源框架RoboGuice, 它的作用跟之前讲过的Dagger框架几乎是一样的,只是Dagger比它的功能更强大一些。Dagger通过专注于一种简化的功能集以一种不同的方式达到了更好的性能。有人认为RoboGuice节约了大量的时间。较少的代码意味着较少的错误,较少的样板代码意味着可以把更多的时间放到应用的核心逻辑上。所以这就是为什么我们要使用这些开源框架来开发的原因。
     下面我们来说说RoboGuice的使用:
  • Views Injection: 我们要想取得一个xml文件中的某个控件对象时,不再采用findViewById(R.id...)这种方式了,而是用@InjectViews注解来实现, 如: @InjectView(R.id.textView1) TextView textView1; //这样我们就得到了这个TextView对象实体                                                                 
  • Resources Injection: 同样也提供了资源的注入方式,也不再是传统的getResources().getDrawable(R.id.ic_launcher)这种方式, 而是用 @InjectResources注解来做, 如: @InjectResource(R.id.ic_launcher) Drawable icLauncher;                                                                          
  • System services Injection: 获取一些系统级服务对象, 不会再沿用原来的
    locManager = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);的方法了,而是运用@Inject注解来实现,如:
    @Inject LocationManager locManager;
  • POJO object Injection: 注入一个简单JAVA对象(POJO)也是用注解@Inject, 如: @Inject Student student;
事实上很多人都认为RoboGuice的效率很低,所以其实很少人愿意用这个,而更多人倾向于用AA (Android Annotation)。
当然RoboGuice中还有一些其他的注解:
@ContentView(R.layout.layout_main) 代替 setContentView(R.layout.layout_main);
@ContextSingleton 来设计一个单例的类。(在dagger中其实都有)
如果网友有兴趣,再去深入研究它的Java Doc(http://www.imobilebbs.com/download/android/roboguice/javadoc/)

Butter Knife

这个框架跟RoboGuice框架的使用方法机会一样,顺带稍微记录一下。
class ExampleActivity extends Activity {
  @InjectView(R.id.user) EditText username;
  @InjectView(R.id.pass) EditText password;

  @OnClick(R.id.submit) void submit() {
    // TODO call server...
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.inject(this);
    // TODO Use "injected" views...
  }
}
Gradle中的配置:
compile 'com.jakewharton:butterknife:5.1.1'

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK