天天看點

Android 注解架構----Butter knife

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;
    }
}
           

繼續閱讀