您的位置:首页 > 移动开发 > Android开发

android-使用butterknife来对代码优化

2014-08-17 08:50 543 查看
刚入职不久,最近公司项目在优化,使用了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。使用视图注入后我们可以少些很多代码,代码看起来也比较清爽很多。

demo下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 重构 优化 控件