android-使用butterknife来对代码优化

本文介绍ButterKnife开源库的使用方法,该库通过视图注入减少Android应用中的findViewById调用,简化代码并提高可读性。文章通过实例展示了如何在Activity中使用ButterKnife进行视图绑定和事件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刚入职不久,最近公司项目在优化,使用了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下载

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值