Android註解架構butterknife基本用法

來源:互聯網
上載者:User

標籤:

現在安卓項目開發中,butterknife是比較常用的註解架構,從而簡化了findViewById的重複使用,提高了編程的效率

然而為什麼要使用butterknife?一方面是為了提高編程效率,一方面butterknife對系統效能是沒有影響的,因為butterknife是在編譯的時候產生新的class,不是運行時進行反射,所以對效能不會有影響

butterknife現在最新版本是butterknife8,不過開發中還是主要使用butterknife6和butterknife7

butterknife6和butterknife7用法還是稍稍有點不同的


(a)引入butterknife註解架構

在Android Studio中可以,很快直接引入,我們可以,選擇項目->右鍵->open modules setting,然後選擇Dependencies,選擇綠色的Add按鈕,輸入com.jakewharton:butterknife:7.0.1或者com.jakewharton:butterknife:6.1.0等等,引入架構,也可以網上下載jar,然後選擇add as library,添加到項目



(b)butterknife的主要用處

(i)Activity類裡使用:

Demo:只要使用InjectView就可以,然後在onCreate方法裡初始化

ButterKnife.inject(類名.this);

   @InjectView(R.id.listview)    ListView listview;    @InjectView(R.id.tv_black)    TextView mBlack;    @InjectView(R.id.message_title)    TextView mTitle;    private HashMap<String,Object> map;    private Context mContext;    @Override    protected void onCreate(Bundle arg0) {        super.onCreate(arg0);        setContentView(R.layout.activity_group_post);        ButterKnife.inject(GroupPostActivity.this);        initView();    }

butterknife7就換成@Bind就可以,初始化換成ButterKnife.bind(this);


(ii)在Fragment類使用

public class SimpleFragment extends Fragment {     @InjectView(R.id.fragment_text_view)    TextView mTextView;     public SimpleFragment() {    }     @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.fragment_simple, container, false);        ButterKnife.inject(this, view);        mTextView.setText("TextView in Fragment are found!");        return view;    }}


(iii)在事件處理裡使用

onClickListener可以這樣寫了

@OnClick(R.id.basic_finish_a_button)    void finishA(View view) {        finish();    }


(iiii)在ListView和GridView裡使用

@InjectViews({R.id.label_first_name, R.id.label_middle_name, R.id.label_last_name})List<TextView> labelViews;

也可以在適配器裡使用等等

下面提供參考文檔

參考部落格:http://blog.csdn.net/u012468376/article/details/50594531(Butterknife7)

http://www.cnblogs.com/mengdd/archive/2015/06/23/4595973.html(Butterknife6)

例子:https://github.com/mengdd/AndroidButterKnifeSample官網: http://jakewharton.github.io/butterknife/Java Doc: http://jakewharton.github.io/butterknife/javadoc/github上開源項目: https://github.com/JakeWharton/butterknife






Android註解架構butterknife基本用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.