1.首先要在项目的build里
dependencies {
classpath 'com.jakewharton:butterknife-gradle-plugin:8.4.0'
}其次添加依赖
compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
在最上添加
apply plugin: 'com.jakewharton.butterknife'
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }
2.封装的
public class MainActivity extends BaseActivity { @BindView(R.id.btn1) Button btn1; @BindView(R.id.btn2) Button btn2; @Override protected void initView() { } @Override protected void initData() { } @Override protected int bindLayoutId() { return R.layout.activity_main; } @OnClick({R.id.btn1,R.id.btn2}) public void a(View view){ switch (view.getId()){ case R.id.btn1: showToast("btn1"); break; case R.id.btn2: showToast("btn2"); break; } } }
2.主方法
public abstract class BaseActivity extends AppCompatActivity{ private final String TAG = BaseActivity.class.getSimpleName(); protected Unbinder unbinder; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(bindLayoutId()); unbinder = ButterKnife.bind(this); initView(); initData(); } /** * 初始化view */ protected abstract void initView(); /** * 初始化数据 */ protected abstract void initData(); /** * 根布局id * @return */ protected abstract int bindLayoutId(); /** * 显示toast * @param msg */ public void showToast(String msg){ Toast.makeText(this,msg,Toast.LENGTH_SHORT).show(); } /** * 无值传递跳转 * @param cls */ public void startActivity(Class<? extends Activity> cls){ Intent intent = new Intent(this,cls); startActivity(intent); } /** * 有值传递跳转 * @param cls */ public void startActivity(Bundle bundle,Class<? extends Activity> cls){ Intent intent = new Intent(this,cls); intent.putExtras(bundle); startActivity(intent); } /** * 是否 * @param flag */ public void isFullScreen(boolean flag){ if(flag){ // TODO: 2018/6/7 全屏的代码 getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); }else { // TODO: 2018/6/7 fei } } @Override protected void onDestroy() { super.onDestroy(); if(unbinder != null){ unbinder.unbind(); //解绑 } } }
3.5布局
<LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/btn2" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>