Android商城開發系列(四)——butterknife的使用


  在上一篇博客:Android商城開發系列(三)——使用Fragment+RadioButton實現商城底部導航欄實現商城的底部導航欄時,里面用到了butterknife,今天來講解一下的butterknife使用

一、butterknife基本概念

  butterknife是一個依賴注入框架,可以省去我們findviewbyid()操作,哈哈~俗話說:“不會偷懶的程序員不是好的程序員!”。作為一名Android開發,是不是經常厭煩了大量的findViewById以及setOnClickListener代碼,而ButterKnife是一個專注於Android系統的View注入框架,讓你從此從這些煩人臃腫的代碼中解脫出來。 

二、示例代碼

  先來看一段代碼示例說明下ButterKnife是如何簡化代碼的:

  采用findViewById( )方法產生的代碼: 

package com.nyl.shoppingmalltest;

import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class MainActivity extends Activity {

    private RadioGroup rg_main;
    private RadioButton rb_home;
    private RadioButton rb_type;
    private RadioButton rb_community;
    private RadioButton rb_user;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化布局
        rg_main = (RadioGroup) findViewById(R.id.rg_main);
        rb_home = (RadioButton) findViewById(R.id.rb_home);
        rb_type = (RadioButton) findViewById(R.id.rb_type);
        rb_community = (RadioButton) findViewById(R.id.rb_community);
        rb_user = (RadioButton) findViewById(R.id.rb_user);
    }
}

  而用ButterKnife之后的代碼是這樣的:

package com.nyl.shoppingmall.activity;

import android.app.Activity;
import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.nyl.shoppingmall.R;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends Activity {
    @Bind(R.id.frameLayout)
    FrameLayout frameLayout;
    @Bind(R.id.rb_home)
    RadioButton rbHome;
    @Bind(R.id.rb_type)
    RadioButton rbType;
    @Bind(R.id.rb_community)
    RadioButton rbCommunity;
    @Bind(R.id.rb_user)
    RadioButton rbUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //ButterKnife和當前Activity綁定
        ButterKnife.bind(this);
      
    }
}

三、用法

  在Android編程過程中,我們會寫大量的布局和點擊事件,像初始view、設置view監聽這樣簡單而重復的操作讓人覺得麻煩類,所以可以采用注解的方式去實現,而ButterKnife則是注解中相對簡單易懂的很不錯的開源框架,接下來就介紹一下如何使用。

3.1 Module 里的 build.gradle 里面引入butterknife

  compile 'com.jakewharton:butterknife:7.0.1'

  

3.2 安裝 butterknife插件

  在 Setting->Plugins 中輸入 butterknife 添加插件,如下圖:

  

  接着就是下載,如下圖:

  

  完成后,如下圖所示:

  

  安裝完成之后重啟AndroidStudio

  見證奇跡的時刻來了,把光標定在setContentView(R.layout.activity_main);然后點擊Code→Generate,如下圖:

  

  勾選需要生成的元素,如下圖所示:

  

  點擊Confim就會生成如下圖所示代碼:

  

  這就是 Butterknife以及關於Butterknife插件的用法,很簡單也很方便,推薦大家在開發中使用Butterknife框架去提高開發效率


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM