Android 注解框架----Butter knife

本文详细介绍了Butterknife库在简化Android开发过程中的优势,包括使用注解替代findViewById、批量操作视图、减少监听器的匿名内部类使用、资源注解等特性。通过实际代码示例展示了如何在页面一、页面二以及适配器中高效地应用Butterknife,以提升开发效率并减少代码冗余。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Butter knife的好处:

Eliminate findViewById calls by using @BindView on fields.//通过使用@BindView淘汰findViewById的调用

Group multiple views in a list or array. Operate on all of them at once with actions, setters, or properties.//在集合或数组中存放多个view,在行为、设置、属性上设置一次,所有的view都能生效。
Eliminate anonymous inner-classes for listeners by annotating methods with @OnClick and others.//通过@OnClick或其它方法注解方法淘汰监听器的匿名内部类使用形式
Eliminate resource lookups by using resource annotations on fields.//通过使用资源注解,摒弃资源查找。

框架在github地址:https://github.com/JakeWharton/butterknife

框架简单使用的官方网址:https://jakewharton.github.io/butterknife/

下文所有代码运行环境均为Android Studio。

首先在项目的Build.gradle文件中添加依赖代码:

buildscript {
  repositories {
    mavenCentral()
   }
  dependencies {
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
  }
}

apply plugin: 'com.neenbedankt.android-apt'

dependencies {
  compile 'com.jakewharton:butterknife:8.0.1'
  apt 'com.jakewharton:butterknife-compiler:8.0.1'
}
如果出现could not find com.android.support:support-annotations:23.3.0的问题,请通过SDK Manager更新一下Android支持库的版本

页面一界面代码:

package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.List;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class MainActivity extends AppCompatActivity {
    @BindView(R.id.text)//注解单个控件,使用的是@BindView
            TextView text;
    @BindViews({R.id.btn, R.id.btn2, R.id.btn3, R.id.go_secondPage})//批量注解控件,使用的是@BindViews
            List<Button> buttons;
    @BindString(R.string.china_value)//注解字符串资源文件
            String china;
    @BindString(R.string.english_value)//注解字符串资源文件
    String eng;
    @BindString(R.string.number_value)//注解字符串资源文件
    String num;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化BUtterKnife框架,可写在项目基类里面。
        ButterKnife.bind(this);

    }
    
    //注解点击事件,注意不要放在Oncreate()等生命周期中,否则编译报错
    @OnClick({R.id.btn, R.id.btn2, R.id.btn3, R.id.go_secondPage})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn:
                text.setText(china);
                break;
            case R.id.btn2:
                text.setText(eng);
                break;
            case R.id.btn3:
                text.setText(num);
                break;
            case R.id.go_secondPage:
                startActivity(new Intent(MainActivity.this, SecondActivity.class));
                break;
        }
    }

}

页面一布局文件代码:

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.example.myapplication.MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_centerInParent="true"
        android:text="改成汉字" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@id/btn"
        android:layout_marginTop="20dp"
        android:text="改成英文" />
    <Button
        android:id="@+id/btn3"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@id/btn2"
        android:layout_marginTop="20dp"
        android:text="改成数字" />
    <Button
        android:id="@+id/go_secondPage"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@id/btn3"
        android:layout_marginTop="20dp"
        android:text="进入列表页面" />
</RelativeLayout>
这样就可以省去大量繁琐的书写findViewById(),而在声明控件的同时,就已经知道了控件在布局文件中的位置,并能随时调用控件。Butter knife同样可以使用在适配器的ViewHolder及fragment中,在 官方使用网站有代码示例,感兴趣的同学可以看一下。下面代码是在适配器中使用Butter knife框架

页面二页面代码:

package com.example.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnItemClick;

/**
 * Created by FZY on 2016/5/3.
 */
public class SecondActivity extends Activity {
    @BindView(R.id.list)
    ListView mList;
    private DataAdapter adapter;
    private List<DataBean> dataList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_second_layout);
        ButterKnife.bind(this);
        initData();

        mList.setAdapter(adapter);


    }

    private void initData() {
        dataList = new ArrayList<>();
        DataBean bean;
        for (int i = 0; i < 20; i++) {
            bean = new DataBean();
            bean.setAddress("中国" + i);
            bean.setName("老王" + i);
            dataList.add(bean);
        }
        adapter = new DataAdapter(dataList, this);
    }

    @OnItemClick(R.id.list)
    public void OnItemClickListener(int pos) {
        DataBean bean = dataList.get(pos);
        if (bean != null) {
            Toast.makeText(SecondActivity.this, "name is " + bean.getName() + " and address is " + bean.getAddress(), Toast.LENGTH_SHORT).show();
        }
    }
}

页面二布局文件代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:minHeight="40dp"
        android:background="#00ff00"
        android:text="PageSecond" />

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:cacheColorHint="#00000000"
        android:listSelector="#00000000"
        android:scrollbars="none"></ListView>
</LinearLayout>

页面二使用适配器页面代码:

package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.List;

import butterknife.BindViews;
import butterknife.ButterKnife;

/**
 * Created by FZY on 2016/5/3.
 */
public class DataAdapter extends BaseAdapter {
    private List<DataBean> list;
    private Context context;

    public DataAdapter(List<DataBean> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public DataBean getItem(int position) {
        return list == null || list.get(position) == null ? null : list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.list_item, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        DataBean bean = getItem(position);
        if (bean != null) {
            ( holder.lists.get(0)).setText(bean.getName());
            ( holder.lists.get(1)).setText(bean.getAddress());
        }
        return convertView;
    }

    class ViewHolder {
    //可以批量注解在集合或数组中,也可以分开单个注解
   @BindViews({R.id.name, R.id.address})
        List<TextView> lists;

        public ViewHolder(View view) {
           ButterKnife.bind(this, view);
        }
    }
}
适配器item布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:gravity="center" />
    <TextView
        android:id="@+id/address"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="3"
        android:gravity="center" />
</LinearLayout>

DataBean代码:

package com.example.myapplication;

/**
 * Created by FZY on 2016/5/3.
 */
public class DataBean {
    private String name;
    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值