編輯:Android 程式設計入門
首頁上方那條不停向上翻動的公告,是 App 裡很常見的元件。它不需要任何第三方庫,本質上就是一個自定義的 LinearLayout,搭配屬性動畫與一個計時器就能完成。
整個元件由四個部分組成:
1. 容器可見區域固定為一個條目高,內部同時存在兩個子 View;
2. 透過 postDelayed 每隔固定間隔觸發一次;
3. 用 ObjectAnimator 讓兩個子 View 一起沿 Y 軸上移一個條目高,營造捲動的錯覺;
4. 動畫結束後把移出畫面的那個 View 重新填上下一筆資料並搬到第二個位置,形成無限循環。
條目本身可掛上點擊事件,因此公告還能連到對應的活動頁。
在 res/values/attrs.xml 中定義滾動間隔與動畫時長:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="NoticeView">
<attr name="gap" format="integer" />
<attr name="animDuration" format="integer" />
</declare-styleable>
</resources>
並在 style 中關閉標題列,讓畫面更精簡:
<style name="AppTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowNoTitle">true</item>
</style>
讀取寫法與所有自定義控制項一致,關鍵是取完之後一定要 recycle,否則會造成記憶體洩漏:
// 取得自定義屬性集合
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.NoticeView);
mAdverHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
jdAdverHeight, getResources().getDisplayMetrics());
int gap = array.getInteger(R.styleable.NoticeView_gap, mGap);
int animDuration = array.getInteger(R.styleable.NoticeView_animDuration, mAnimDuration);
// 釋放 TypedArray,避免記憶體洩漏
array.recycle();
條目由一個左側標籤與一個右側標題組成,標題過長時以省略號收尾:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="@drawable/blue_line_bg4"
android:layout_marginTop="10dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="10dp"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="@+id/tag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:background="@drawable/blue_line_bg"
android:padding="5dp"
android:text="最新"
android:textColor="#ff0000" />
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:ellipsize="end"
android:singleLine="true"
android:text="價格驚呆!電信千兆光纖上市"
android:textColor="#000000"
android:textSize="12sp" />
</LinearLayout>
package com.notice.scroll;
public class NoticeEntity {
public String title;
public String url;
public NoticeEntity(String title, String url) {
super();
this.title = title;
this.url = url;
}
}
package com.notice.scroll;
import java.util.List;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class NoticeAdapter {
private List<NoticeEntity> mDatas;
public NoticeAdapter(List<NoticeEntity> datas) {
this.mDatas = datas;
if (datas == null || datas.isEmpty()) {
throw new RuntimeException("nothing to show");
}
}
/** 資料筆數 */
public int getCount() {
return mDatas == null ? 0 : mDatas.size();
}
/** 取得指定位置的資料 */
public NoticeEntity getItem(int position) {
return mDatas.get(position);
}
/** 產生條目 View */
public View getView(NoticeView parent) {
return LayoutInflater.from(parent.getContext()).inflate(R.layout.item, null);
}
/** 把資料綁到條目上,並掛上點擊事件 */
public void setItem(final View view, final NoticeEntity data) {
TextView tv = (TextView) view.findViewById(R.id.title);
tv.setText(data.title);
TextView tag = (TextView) view.findViewById(R.id.tag);
tag.setText(data.url);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 這裡可以改成開啟 data.url 對應的頁面
Toast.makeText(view.getContext(), data.url, Toast.LENGTH_SHORT).show();
}
});
}
}
package com.notice.scroll;
public class NoticeView extends LinearLayout {
private float mAdverHeight = 0f; // 單一條目高度
private final int mGap = 4000; // 滾動間隔(毫秒)
private final int mAnimDuration = 1000; // 動畫時長(毫秒)
private final float TEXTSIZE = 20f;
private final float jdAdverHeight = 50;
private NoticeAdapter mAdapter;
private View mFirstView;
private View mSecondView;
private int mPosition; // 目前播放到哪一篇
private boolean isStarted; // 是否已在滾動
private Paint mPaint;
public NoticeView(Context context) {
this(context, null);
}
public NoticeView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public NoticeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
setOrientation(VERTICAL);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.NoticeView);
mAdverHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
jdAdverHeight, getResources().getDisplayMetrics());
int gap = array.getInteger(R.styleable.NoticeView_gap, mGap);
int animDuration = array.getInteger(R.styleable.NoticeView_animDuration, mAnimDuration);
if (gap <= animDuration) {
gap = mGap;
animDuration = mAnimDuration;
}
array.recycle();
}
/** 設定資料 */
public void setAdapter(NoticeAdapter adapter) {
this.mAdapter = adapter;
setupAdapter();
}
/** 開始滾動 */
public void start() {
if (!isStarted && mAdapter.getCount() > 1) {
isStarted = true;
postDelayed(mRunnable, mGap);
}
}
/** 停止滾動 */
public void stop() {
removeCallbacks(mRunnable);
isStarted = false;
}
private void setupAdapter() {
removeAllViews();
if (mAdapter.getCount() == 1) {
// 只有一筆資料,不需要滾動
mFirstView = mAdapter.getView(this);
mAdapter.setItem(mFirstView, mAdapter.getItem(0));
addView(mFirstView);
} else {
mFirstView = mAdapter.getView(this);
mSecondView = mAdapter.getView(this);
mAdapter.setItem(mFirstView, mAdapter.getItem(0));
mAdapter.setItem(mSecondView, mAdapter.getItem(1));
addView(mFirstView);
addView(mSecondView);
mPosition = 1;
isStarted = false;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (LayoutParams.WRAP_CONTENT == getLayoutParams().height) {
getLayoutParams().height = (int) mAdverHeight;
} else {
mAdverHeight = getHeight();
}
if (mFirstView != null) {
mFirstView.getLayoutParams().height = (int) mAdverHeight;
}
if (mSecondView != null) {
mSecondView.getLayoutParams().height = (int) mAdverHeight;
}
}
/** 垂直翻滾:兩個 View 一起沿 Y 軸上移 */
private void performSwitch() {
ObjectAnimator animator1 = ObjectAnimator.ofFloat(mFirstView, "translationY",
mFirstView.getTranslationY() - mAdverHeight);
ObjectAnimator animator2 = ObjectAnimator.ofFloat(mSecondView, "translationY",
mSecondView.getTranslationY() - mAdverHeight);
AnimatorSet set = new AnimatorSet();
set.playTogether(animator1, animator2);
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mFirstView.setTranslationY(0);
mSecondView.setTranslationY(0);
View removedView = getChildAt(0);
mPosition++;
mAdapter.setItem(removedView, mAdapter.getItem(mPosition % mAdapter.getCount()));
removeView(removedView);
addView(removedView, 1);
}
});
set.setDuration(mAnimDuration);
set.start();
}
private AnimRunnable mRunnable = new AnimRunnable();
private class AnimRunnable implements Runnable {
@Override
public void run() {
performSwitch();
postDelayed(this, mGap);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
stop();
}
}
兩個容易被忽略的細節:動畫結束後務必把 translationY 歸零,否則下一輪會從錯誤的位置開始;onDetachedFromWindow 中要停止計時器,避免離開畫面後仍在空轉。
public class ScrollNoticeActivity extends Activity {
private List<NoticeEntity> mDataList = new ArrayList<NoticeEntity>();
private NoticeAdapter mNoticeAdapter;
private NoticeView mNoticeView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
}
private void initData() {
mDataList.add(new NoticeEntity("剩餘流量查詢 XXXXXXXX", "最新"));
mDataList.add(new NoticeEntity("恭喜你中了 5000w 大獎!", "最火爆"));
mDataList.add(new NoticeEntity("新入網用戶領取福利專區", "HOT"));
mDataList.add(new NoticeEntity("溫馨提示:此乃詐騙訊息", "new"));
mNoticeAdapter = new NoticeAdapter(mDataList);
mNoticeView = (NoticeView) findViewById(R.id.tv_notices);
mNoticeView.setAdapter(mNoticeAdapter);
mNoticeView.start(); // 啟動滾動
}
}
如果只需要顯示單行文字,其實不必自定義控制項。用一個 TextView 搭配 Handler 每兩秒換一次文字,也能達到類似效果:
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
int index = msg.arg1 + 1;
if (index >= mDataList.size()) {
index = 0;
}
mNoticeTextView.setText(mDataList.get(index).title);
mHandler.sendMessageDelayed(mHandler.obtainMessage(1, index, 0), 2000);
break;
default:
break;
}
}
};
兩種做法的差別在於:Handler 版本是直接替換文字,視覺上是硬跳;NoticeView 版本有補間動畫,過場柔和,而且能同時露出兩個條目、支援個別點擊,正式專案通常以前者為骨架、後者為體驗加分項。
Android 按鈕事件綁定的五種常見寫法
在 Android 開發中,按鈕事件綁定有多種寫法。不同寫法適合不同場景,理解各自的特性有助於組織更清晰的程式結構。一、匿名內部類匿名內部類是最常見的事件監聽寫法,適合只
Android 開發入門:專案目錄結構與清單檔配置
Android 專案的目錄結構如下: 資源資料夾: 清單配置檔 Android 的四大元件在使用前,都必須先在清單檔(AndroidManifest.xml)中完成配
Android 應用閃退(Crash)分析與捕獲機制
問題描述 閃退(Crash)是指客戶端程式在執行時遭遇無法處理的例外或錯誤而被迫結束的現象。要系統性地處理它,需要回答兩個問題:Crash 發生的原因如何分類、各對應什麼
Android 序列化實戰:Serializable 與 Parcelable 全面比較
還有幾天開學,先來一發,把序列化這塊整理清楚。 學習路線 序列化的目的 Android 中序列化的兩種方式 Parcelable 與 Serializable 的效能