你还在苦逼地findViewById吗?使用ButterKnife从此轻松定义控件

前段时间笔者在苦逼地撸代码~最后发现有些复杂的界面在写了一屏幕的findviewbyid~~~另一堆setOnXXXListener~有没有方便一点的方法让我们简单点不用每次都定义一次。find一次,强转一次,set一次~~

后来笔者在收藏夹里找到同事好久曾经发给我的网址(呵呵,果然是一旦增加了收藏夹就再也不会看了)~~打开发现有个叫做butterknife的东东~


那么接下来我们来看看ButterKnife如何将我们从findviewbyid中挽救出来的。



ButterKnife简单介绍

呵呵,butterknife是一个关于基于注解的框架~~然后就没有然后了


ButterKnife的下载与配置

ButterKnife框架是一个jar包。大家能够到官网上下载也能够到文章末尾的附件中下载。

1.把下载到的jar包放在android项目的libs目录里面

2.然后单击项目---Alt+enter-----》java Compiler-----》Annotation Procession------》勾一下 钩一下 Enable project specific settings 

------》Factory Path ( 钩一下Enable project specific settings )----》add jar--->选择刚放进libs的jar包。

然后ok~~


ButterKnife的使用


首先上一个布局文件。这个布局文件非常easy仅仅有一个button:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.mytestproject.MainActivity" >

  <Button 
      android:id="@+id/test"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="点我一下"
      />

</RelativeLayout>
然后看MainActivity:
package com.example.mytestproject;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class MainActivity extends Activity {
	 @Bind(R.id.test)
     Button testBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.test)
    public void sayHi(View view) {
    	testBtn.setText("Hello!");
    }
}

最后执行一下程序能够看到button上面的文字从"点我一下"变成了"Hello"
在定义控件的时候仅仅需在所定义的空间上加上@Bind(viewId)就能够啦
然后为控件绑定事件的时候:以onClick事件为例,在方法的上面增加@OnClick(ViewId)就能够了
当中方法名称是随开发人员定义的,里面的參数能够有也能够没有。比方上面代码中的:

 @OnClick(R.id.test)
    public void sayHi(View view) {
    	testBtn.setText("Hello!");
    }
能够写成:
 @OnClick(R.id.test)
    public void sayHi() {
    	testBtn.setText("Hello!");
    }
依旧能够的。參数写与不写就看实际应用了。
还有定义控件的时候不能定为私有:
private TextView tv;//这样是不能够的

与传统findViewById比較

(本文基于Eclipse)
看上去是比findViewById更简便一些,可是假设在Android Studio上使用这个框架那才爽~~一键生成控件~~
有兴趣的朋友能够去研究一下~~

最后提醒一句使用的时候别忘记调用一下:
 ButterKnife.bind(this);
否则注解是无法生效的





原文地址:https://www.cnblogs.com/cynchanpin/p/6916468.html