編輯:關於 Android 程式設計
在電商類應用或引導頁中,經常會看到自動輪播的廣告條。這種效果可以通過 ViewPager 搭配定時器與底部指示點來實現。
布局中上方放置 ViewPager,用於承載輪播圖片;下方放置 TextView 與 LinearLayout,分別顯示描述文字與指示點。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="200dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/viewpager"
android:background="#33000000"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="@+id/image_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="@android:color/white" />
<LinearLayout
android:id="@+id/show_pointer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
可以開啟一個線程,每隔一段時間讓 ViewPager 切換到下一頁。切換操作需要回到主線程執行。
new Thread(() -> {
while (!isStop) {
SystemClock.sleep(5000);
runOnUiThread(() -> mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1));
}
}).start();
底部指示點可以根據圖片數量動態添加。每個指示點使用 View 表示,並通過背景 selector 切換選中與未選中狀態。
for (int id : ivIDs) {
iv = new ImageView(this);
iv.setBackgroundResource(id);
imageViewlist.add(iv);
View v = new View(this);
LayoutParams params = new LayoutParams(8, 8);
params.leftMargin = 12;
v.setLayoutParams(params);
v.setEnabled(false);
v.setBackgroundResource(R.drawable.pointer_selector);
layoutPGroup.addView(v);
}
未選中時使用半透明圓點:
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="oval">
<corners android:radius="0.5dip" />
<solid android:color="#55000000" />
</shape>
選中時使用更明亮的圓點:
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="oval">
<corners android:radius="0.5dip" />
<solid android:color="#aaFFFFFF" />
</shape>
最後通過 selector 讓 View 根據 enabled 狀態切換背景:
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_enabled="true" android:drawable="@drawable/pointer_focus" />
<item android:state_enabled="false" android:drawable="@drawable/pointer_disable" />
</selector>
在 Activity 銷毀時,記得停止線程,避免資源洩漏。透過上述方式,即可實現一個簡潔穩定的廣告輪播效果。
用 ViewPager 實現 Gallery 效果:中間大圖、兩側小圖展示
一般情況下,ViewPager 一頁只能顯示一項資料。但我們常看到,特別是電視機頂盒的首頁,中間是一張大圖、兩側還各露出半張小圖。這種效果該怎麼做呢?先看一張成果圖:
ANDROID 設計模式應用(一):創建型模式全解析
所謂模式,就是在某一情境下解決某個問題的固定方案。所有的創建型模式,都是用作「對象的創建或實例化」的解決方案。本文結合影 Android 系統源碼,逐一剖析常見的創建型模
Android 4.4 WebView 硬件渲染:Chromium 内核中那几个"不一样"的类
Android 4.4 的 WebView 换成了 Chromium 内核,但它的硬件渲染路径和原生 Chromium 差别很大。原生 Chromium 依赖多进程 GP
Android 自定義 ImageView 手勢縮放與拖曳實作指南
效果展示 本文要實作的是一個可以縮放與移動的 ImageView。以下先提供效果示意: 範例會把一張圖片放入自定義控制項中,讓使用者可以用手勢放大、縮小,也可以拖曳到不