編輯:關於 Android 程式設計
Android 4.4 之後推出了 Toolbar,只要調整應用的 style 屬性,就能為標題欄填色——可以是系統主題色,也可以是自訂顏色。這效果在 iOS 上早就是標準配備,但在 Android 上仍相對少見。
iOS 的 NavigationBar 最常見兩種效果:一種是轉場動畫(多出現於兩個頁面切換時),另一種是隨手勢滑動背景漸變(多出現於詳情頁)。本文要做的就是後者——一個會隨列表滾動逐漸浮現的漸變標題欄。
出發點是把手機上方狀態列的顏色背景隱藏掉。這裡有個坑:在小米、魅族(大概 MIUI 6 以上)機型裡,狀態列上的時間等文字預設是白色。若 Toolbar 背景是深色,沒問題;但若是淺色背景,這些文字很可能就看不見了。所以第一步是調整狀態列的相關樣式。
先在 style 中配置:
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="android:windowBackground">@color/devide</item>
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:textColorSecondary">@color/white</item>
<item name="android:textColorPrimary">@color/white</item>
<item name="toolbarStyle">@style/ToolbarStyle</item>
<item name="colorControlNormal">@android:color/white</item>
</style>
<style name="ToolbarStyle" parent="Widget.AppCompat.Toolbar">
<item name="contentInsetStart">0dp</item>
<item name="colorControlNormal">@android:color/white</item>
</style>
</resources>
然後把狀態列設為透明:
private void setTranslucentWindows(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// 透明狀態列
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
以下是我寫的標題欄佈局。注意 fitSystemWindows="true" 與最初的背景色設定,這兩者是後續漸變效果的基礎:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="@+id/layout_toolbar_my_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/base"
android:fitSystemWindows="true"
android:paddingBottom="0dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/layout_toolbar_details_back"
android:layout_width="60dp"
android:layout_height="match_parent"
android:onClick="onBack">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:src="@mipmap/btn_back" />
</RelativeLayout>
<TextView
android:id="@+id/text_toolbar_index"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="我是一個標題"
android:textColor="@color/white"
android:textSize="17dp"
android:visibility="gone" />
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
把標題欄佈局引入界面佈局後,相當於在 RecyclerView 的 header 上疊了一層透明標題欄。
漸變效果的關鍵在於:監聽滑動事件,當滑動距離正好等於 header 圖片高度(圖片被完全遮蓋)時,標題欄文字出現;同時用「當前滾動量 / 總滾動距離」的百分比去控制標題欄背景的不透明度。
關於文字出現的時機,建議看交互稿:若大圖下方本身有標題文字,一般應等它被遮蓋之後,標題欄上的標題才淡入,這樣視覺上才不會出現兩處標題並存的突兀感。
這裡有個必須注意的細節:在 onCreate 中呼叫 View 的 getMeasuredHeight() 或 getWidth() 會得到 0,因為此時 View 還沒走完測量與繪製流程。有兩種解法:一是像下面這樣用 post() 延後到 layout 完成之後再取值;二是註冊 ViewTreeObserver 的監聽回呼。
public class MainActivity extends AppCompatActivity {
@Bind(R.id.recycler) RecyclerView recyclerView;
@Bind(R.id.layout_toolbar_my_container) RelativeLayout layoutToolBarBackground;
@Bind(R.id.text_toolbar_index) TextView centerText;
private ArrayList<Model> modelList = new ArrayList<>();
private MyRecyclerAdapter adapter;
private LinearLayoutManager layoutManager;
private int itemIndex;
private ToolBarBackgroundController toolBarBackgroundController;
// header 圖片高度減去標題欄高度,作為漸變的基準距離
private int anchorHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTranslucentWindows(this);
ButterKnife.bind(this);
layoutManager = new LinearLayoutManager(this.getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(this,
DividerItemDecoration.VERTICAL_LIST, R.drawable.devide_line_gray, 0));
initHead();
initData();
initView();
}
private void initHead() {
layoutToolBarBackground.setBackgroundColor(Color.TRANSPARENT);
toolBarBackgroundController = new ToolBarBackgroundController(layoutToolBarBackground);
}
/** 封裝標題欄的透明/不透明切換 */
public class ToolBarBackgroundController {
private View layoutToolbar;
public ToolBarBackgroundController(View layoutToolbar) {
this.layoutToolbar = layoutToolbar;
layoutToolbar.setBackgroundColor(Color.TRANSPARENT);
}
public void setTransparent(boolean needTransparent) {
if (needTransparent) {
centerText.setVisibility(View.GONE);
} else {
layoutToolbar.setBackgroundColor(getResources().getColor(R.color.base));
centerText.setVisibility(View.VISIBLE);
}
}
}
private int getStatusBarHeight(Context context) {
int resourceId = context.getResources()
.getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
return context.getResources().getDimensionPixelSize(resourceId);
}
return 0;
}
private void initData() {
for (int i = 0; i < 20; i++) {
Model model = new Model();
model.setName("jjq" + i);
model.setDesc("哈哈哈哈哈哈哈哈");
modelList.add(model);
}
}
private void initView() {
if (adapter == null) {
adapter = new MyRecyclerAdapter();
} else {
adapter.notifyDataSetChanged();
}
adapter.initData(false);
adapter.appendData(modelList);
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new OnScrollColorChangeListener());
}
/** 滾動監聽:核心漸變邏輯 */
private class OnScrollColorChangeListener extends RecyclerView.OnScrollListener {
private boolean isTrans = true;
private int y = 0;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (anchorHeight != 0) {
y += dy;
boolean needTrans = y <= anchorHeight;
if (needTrans != isTrans) {
// 跨過臨界點:直接切換狀態
isTrans = needTrans;
toolBarBackgroundController.setTransparent(needTrans);
} else {
// 未跨過臨界點:按比例調整 alpha
if (y / anchorHeight < 1) {
layoutToolBarBackground.setBackgroundColor(
getResources().getColor(R.color.base));
layoutToolBarBackground.getBackground()
.setAlpha((int) ((float) y / anchorHeight * 255));
}
}
}
}
}
private class MyHeaderItemHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
public MyHeaderItemHolder(View itemView, Context context) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.img_main_recycler_head_banner);
// 等 header 佈局完成後再取高度,否則會拿到 0
imageView.post(new Runnable() {
@Override
public void run() {
anchorHeight = imageView.getMeasuredHeight()
- layoutToolBarBackground.getMeasuredHeight();
}
});
}
}
// Adapter 其餘部分從略
}
上面這個 Demo 能跑,但如果要放進正式專案,有幾處建議調整:
y / anchorHeight 是整數除法,永遠得 0 或 1。原意應該是 (float) y / anchorHeight。這是一個很容易寫錯又不容易發現的 bug——它會讓 alpha 一直是 0,看起來就像漸變完全沒生效。getResources().getColor() 已標記為 deprecated,建議改用 ContextCompat.getColor() 或 getColor(int, Theme)。ColorDrawable 並反覆呼叫 setAlpha(),避免高頻率配置對象帶來的 GC 壓力。CoordinatorLayout + AppBarLayout + CollapsingToolbarLayout,透過 AppBarLayout.OnOffsetChangedListener 拿到偏移比例即可,無需自己算 header 高度、也無需 post 延遲取值的技巧。自己實作的好處是完全可控,適合有高度客製化需求的場景。最後補一個小技巧:若標題欄上的文字太長,可以為 TextView 加上跑馬燈效果——設定 ellipsize="marquee" 與 marqueeRepeatLimit="marquee_forever",並記得給它 android:focusable="true",否則在部分機型上不會滾動。
Demo 到此完成。這套「監聽滾動距離 → 換算比例 → 調整 alpha」的思路,其實可以套用到任何需要隨滾動變化的元素上,不只是標題欄。
自己實作 Android 側滑菜單
效果與思路側滑菜單是 Android 應用中常見的互動模式。早期常使用 SlidingMenu,5.0 之後也有官方的 DrawerLayout。若想理解底層原理,可以利
Android 開發之 DatePicker 與 TimePicker 日期時間選擇控件
DatePicker 繼承自 FrameLayout,作用是向用戶提供年、月、日三個維度的日期數據,並允許其修改。 TimePicker 同樣繼承自 FrameLay
Android 入門:用 XML 构建基礎動畫
首先在 res 目錄下新建一個名為 anim 的文件夾,在其中建立 XML 檔,例如 a1.xml。<set xmlns:android=https://schem
Android 集成 ZXing:二維碼的生成、解圖與掃描
一、二維碼是什麼 二維碼是在平面(縱橫兩個方向)上按特定規律分佈的黑白方塊圖形,用來記錄數據符號信息。它在編碼上巧妙借用了計算機邏輯基礎的 0 和 1 比特流概念,用若干