剛入職不久,最近公司項目在優化,使用了butterknife開源jar包來進行代碼重構,一定程度上減少了代碼,而且代碼看起來清爽多了。下面我們一起看看這神奇的butterknife
先導入jar包
剩下的配置是關鍵
配置完後就可以開始編寫了。今天就以一個簡單的layout來說,後面再逐步增加各種佈局的使用demo
好,先來看看我們的xml,沒多少東西
<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=".MainActivity" >
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tv"
android:text="@string/button"
/>
</RelativeLayout>
再看我們的activity
package com.example.injectviewdemo;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
* InjectView使用demo
* @author hjhrq1991
* @deprecated date 2014-8-16 23:43:29
*/
public class MainActivity extends Activity{
//使用視圖注入來找到id,這個工作自動完成
@InjectView(R.id.tv) TextView mTv;
@InjectView(R.id.btn) Button mBtn;
// private TextView mTv;
// private Button mBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// mTv = (TextView) findViewById(R.id.tv);
// mBtn = (Button) findViewById(R.id.btn);
//感覺很神奇對吧,代碼少了很多,當然,這種方法不是什麼情況都適用的,小編經過多種佈局的測試,發現在普通佈局上可以,但是在複雜佈局上不是很實用。
//不過在Adapter、Fragment也可以使用,確實能夠減少不少代碼
ButterKnife.inject(this);
mTv.setText("Please click me!");
// mTv.setOnClickListener(this);
// mBtn.setOnClickListener(this);
}
//直接使用onclck事件,不用繼承ClickListener接口setClickListener等等。
@OnClick({ R.id.tv, R.id.btn })
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv:
Toast.makeText(getApplication(), "You has clicked the text!", 100).show();
break;
case R.id.btn:
mTv.setText("You has clicked the button!");
Intent intent = new Intent(this,ListViewActivity.class);
startActivity(intent);
break;
}
}
}
使用方法比較簡單,不過在佈局比較複雜,比較多控件的時候,我們要寫一大堆的findbyid,然後還得setonclicklistener。使用視圖注入後我們可以少些很多代碼,代碼看起來也比較清爽很多。