編輯:關於 Android 程式設計
ButterKnife 是一個依賴注入框架,可以省去繁瑣的 findViewById() 操作。過去一直使用 xUtils 的注入功能,這次實際體驗 ButterKnife 後,發現兩者之間存在一些差異。
使用 @InjectView(R.id.xxx) 標註欄位即可省去 findViewById,但需注意被標註的 TextView 不能宣告為 private 或 static,否則會報錯(xUtils 則無此限制)。
此外,@OnLongClick(R.id.xxx) 這類事件綁定的方法同樣不能是 private,且回傳型別必須為 boolean。
1. 添加依賴:
compile 'com.jakewharton:butterknife:6.1.0'
2. 版面配置:
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/bt_changetext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="改變文字" />
</RelativeLayout>
3. Activity 程式碼:
public class MainActivity extends ActionBarActivity {
@InjectView(R.id.tv_hello)
TextView tv_hello;
@InjectView(R.id.bt_changetext)
Button bt_changetext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
}
@OnLongClick(R.id.bt_changetext)
boolean changeTextByLongClick() {
tv_hello.setText("hello my dear graypn!");
return true;
}
}
可以看到,透過 ButterKnife 的註解,原本冗長的 findViewById 與 setOnClickListener 都被大幅簡化,程式碼更為乾淨直觀。只要在 onCreate 中呼叫 ButterKnife.inject(this),即可完成所有綁定。
Android 懸浮窗適配全景:各機型、各系統版本的權限處理方案
懸浮窗看起來只是「在別的介面上層畫一個 View」,但在 Android 上,它牽涉到一項獨立管制的權限:SYSTEM_ALERT_WINDOW。這項權限的授予方式在不同
用 MediaRecorder 實作 Android 錄像功能
本文用 MediaRecorder 實作一個可用的錄像功能,包含鏡頭預覽、開始與停止錄製,以及在頂部即時顯示錄製時長。 實作思路 用一個 SurfaceView 承載相
Android 實現圖片圓角的程式碼
下圖為圓角效果示意: 透過 Bitmap、Canvas 與 PorterDuff 混合模式,可以將圖片的四角處理成圓角。核心思路是:先建立一張與原圖相同尺寸並帶透明通道
Android 網絡開發與優化:從 HTTP Client 到請求封裝
寫在前面:網絡能力為何重要 對多數 Android 應用而言,網絡是最關鍵的能力之一。無論是下載資料、上傳表單、同步狀態,還是載入圖片,背後都離不開網絡請求。然而,真正要