码迷,mamicode.com
首页 > 移动开发 > 详细

Android 依赖注入 ButterKnife 基本使用

时间:2016-07-08 17:50:01      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

ButterKnife 是一个快速 Android View 注入框架,开发者是Jake Wharton,简单的来说,ButterKnife 是用注解的方式替代findViewById和setXXXListener

项目GitHub地址:https://github.com/JakeWharton/butterknife/

Android Studio 配置步骤可以直接参考Github上的介绍,很简单。

ButterKnife 是在编译时注解,不会在运行时产生负担,Build工程后你会发现它生成了需要的代码,即它不是使用反射或者在运行时生成代码,所以它不会导致任何性能问题,也不会影响应用速度。

 

看过下面这句话,使用之后发现挺有道理。

ButterKnife 不能算是一个真正的注入,更像是View的代言。

 

1. 替代findViewById()

在变量声明的时候加上注解,如果找不到id,会在编译时报错,注意View变量声明的时候不能为private或者static。

@BindView(R.id.hello_world_tv)
TextView helloWorldTv;
@BindView(R.id.a_hello_world_btn)
Button aHelloWorldBtn;

在setContentView(view)后设置bind()。

setContentView(R.layout.activity_main);
// ButterKnife.inject(this) should be called after setContentView()
ButterKnife.bind(this);

ButterKnife 同样可以在Fragment、Adapter中使用,注意Fragment中要在onDestroyView()中调用unbind()。

public class SimpleFragment extends Fragment {
    private Unbinder unbinder;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_simple, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        unbinder.unbind();
        super.onDestroyView();
    }
}

 

2. 设置监听

ButterKnife 支持设置多种Listener,注意这里的方法仍然不能是private和static

@OnClick
@OnLongClick
@OnPageChange
OnPageChange.Callback
@OnTextChanged
OnTextChanged.Callback
@OnTouch
@OnItemClick
@OnItemLongClick
@OnCheckedChanged

具体使用方法有待继续学习。

 

3. 绑定资源

注意变量声明同样不能为private或者static。

    @BindString(R.string.app_name)
    String appName;//sting
    @BindColor(R.color.red)
    int textColor;//颜色
    @BindDrawable(R.mipmap.ic_launcher)
    Drawable drawable;//drawble
    @BindDrawable(R.drawable.selector_image)
    Drawable selector;

 

4. 多个View进行统一操作

未使用,带学习。

 

 

参考:

http://blog.csdn.net/itjianghuxiaoxiong/article/details/50177549

http://blog.csdn.net/jdsjlzx/article/details/51281844

 

待学习:

1. 常用Listener的使用

2. butterknife 源码分析

 

Android 依赖注入 ButterKnife 基本使用

标签:

原文地址:http://www.cnblogs.com/fansen/p/5653887.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!