Android中最佳实践@BindView代替繁琐的findViewById

ButterKnife

ButterKnife是一个专注于Android系统的View注入框架,以前总是要写很多findViewById来找到View对象,
有了ButterKnife可以很轻松的省去这些步骤。是大神JakeWharton的力作,目前使用很广。
最重要的一点,使用ButterKnife对性能基本没有损失,因为ButterKnife用到的注解并不是在运行时反射的,
而是在编译的时候生成新的class。项目集成起来也是特别方便,使用起来也是特别简单。

使用方法:

1、在build.grade(Moudle)中添加如下依赖

	//butterknife
    implementation 'com.jakewharton:butterknife:10.0.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.0.0'

2、在Activity中使用

  @BindView(R.id.iv_back)
    ImageView img_back;
    @BindView(R.id.blog_content)
    TextView text_content;
    @BindView(R.id.blog_title)
    TextView text_title;
    @BindView(R.id.blog_createTime)
    TextView text_createTime;
    @BindView(R.id.blog_comment_num)
    TextView text_comments;
    @BindView(R.id.blof_prefers)
    TextView text_prefers;
    @BindView(R.id.blog_user_name)
    TextView text_username;

3、在onCreate()方法中注册(重要)

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blog);
        ButterKnife.bind(this);//注意位置 否则报错
    }

4、在Adapter中使用

class LinearViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_title)
        TextView tv_title;
        @BindView(R.id.tv_content)
        TextView tv_content;
        @BindView(R.id.blog_prefers)
        TextView tv_prefers;
        @BindView(R.id.blog_views)
        TextView tv_views;
        @BindView(R.id.blog_user_name)
        TextView tv_username;
        @BindView(R.id.line_index)
        LinearLayout linearLayout;
        @BindView(R.id.blog_avatar)
        ImageView imageView;
 
        public LinearViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);//注意
        }
    }

5、在Fragment中使用

  @BindView(R.id.me_avatar)
    ImageView imageView;
    @BindView(R.id.me_username)
    TextView text_username;
    @BindView(R.id.me_description)
    TextView text_userDcrp;
 
    ApiService apiService;
 
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, 
    @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user, container, false);
        ButterKnife.bind(this, view);//注意
        initData();
        return view;
    }
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值