本文記錄一個 Android 專案從零搭建的核心步驟,重點講解 Gradle 多模塊統一配置、依賴管理優化,以及 ButterKnife 視圖綁定框架的高效使用技巧。
為解決國內訪問 jcenter 慢的問題,優先配置本地倉庫與開源中國鏡像:
buildscript {
repositories {
mavenLocal()
maven { url 'https://maven.oschina.net/content/groups/public/' }
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
}
}
allprojects {
repositories {
mavenLocal()
maven { url 'https://maven.oschina.net/content/groups/public/' }
}
}
避免每個模塊重複配置 compileSdkVersion、buildToolsVersion 等公共屬性:
subprojects {
configure(allprojects - project(':demo')) {
apply plugin: 'com.android.library'
android {
compileSdkVersion 23
buildToolsVersion '23.0.2'
defaultConfig {
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
lintOptions { abortOnError false }
}
dependencies {
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.2'
}
}
}
新建模塊時僅需聲明特有依賴,大幅減少樣板代碼。
採用 Material Design 組件庫,核心組件包括:
CoordinatorLayout + AppBarLayout + CollapsingToolbarLayout 實現折疊標題欄Toolbar 替代傳統 ActionBarNestedScrollView + RecyclerView + CardView 構建列表compile 'com.jakewharton:butterknife:8.x.x'(版本根據項目調整)public class MainActivity extends AppCompatActivity {
@BindView(R.id.btn_submit) Button submitBtn;
@BindView(R.id.tv_title) TextView titleTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this); // 必須在 setContentView 之後調用
}
}
public class DemoFragment extends Fragment {
@BindView(R.id.btn_action) Button actionBtn;
private Unbinder unbinder;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_demo, container, false);
unbinder = ButterKnife.bind(this, view); // 綁定到 View
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind(); // 必須解綁,防止內存洩漏
}
}
// 單個點擊事件
@OnClick(R.id.btn_submit)
public void onSubmitClick() { /* ... */ }
// 多個 View 共用邏輯
@OnClick({R.id.btn_1, R.id.btn_2, R.id.btn_3})
public void onMultiClick(Button button) {
switch (button.getId()) {
case R.id.btn_1: /* ... */ break;
// ...
}
}
// 參數自動轉換
@OnClick(R.id.btn_greet)
public void sayHi(Button btn) {
btn.setText("Hello!");
}
ButterKnife 在編譯期生成類似如下代碼,運行期零反射,性能無損:
public void bind(MainActivity activity) {
activity.submitBtn = (Button) activity.findViewById(R.id.btn_submit);
activity.titleTv = (TextView) activity.findViewById(R.id.tv_title);
}
統一 Gradle 配置提升構建可維護性,ButterKnife 消除 findViewById 囉嗦代碼,配合 Zelezny 插件開發效率倍增。下一篇將詳細講解 CoordinatorLayout 系列組件的協同交互實現。