編輯:關於 Android 程式設計
公司新產品上線需要加入彈幕功能,於是花了一天時間寫了一個 Demo。本文記錄從思路到實作的完整過程,分享給有需要的朋友。
最終效果如下:

1、首先實作一個自訂 Layout,在其中取得需要展示的彈幕陣列,每個彈幕項包含文字內容與圖片 Url 位址。
2、在 Layout 內部使用 Handler 或計時執行緒循環發送彈幕。
3、彈幕採用自訂 View,搭配動畫實現滾動呈現。
總結之後發現,主要難點在於彈幕出現位置的選擇,以及如何確保彈幕及時銷毀(一開始除錯時還真的出現了滿屏彈幕的壯觀場景),還有組件的複用與效能優化。此外還需要處理:透過 Url 載入圖片(可搭配圖片快取框架)、防止彈幕堆疊(這個演算法相對容易)。
後來發現自己寫一個自訂彈幕 View(左邊圓形頭像、右邊文字、橢圓半透明背景)有點麻煩,於是借用了 ListView 中 item 複用的思想,用一個 Item 佈局輕鬆解決。
1、主佈局:彈幕區域的位置可以自行調整,理論上可放在畫面任一位置。
barrageview_test.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.whale.nangua.toquan.view.BarrageView
android:id="@+id/barrageview"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="@drawable/testbackground" />
</RelativeLayout>
2、彈幕 item 佈局:使用自訂的圓形圖片類實現圓形頭像效果。
barrageview_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:background="@drawable/barrage_shape"
android:orientation="horizontal">
<com.whale.nangua.toquan.view.NGNormalCircleImageView
android:id="@+id/barrageview_item_img"
android:layout_width="50dp"
android:layout_height="match_parent"
android:src="@drawable/pumpkin" />
<TextView
android:id="@+id/barrageview_item_tv"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:gravity="center"
android:maxEms="10"
android:singleLine="true"
android:text="測試彈幕"
android:textColor="@android:color/white" />
</LinearLayout>
3、測試用的 Activity:
public class TestAty extends Activity {
BarrageView barrageview;
ArrayList<Barrage> date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.barrageview_test);
initView();
}
private void initView() {
date = new ArrayList<>();
for (int i = 0; i < 100; i++) {
date.add(new Barrage("測試彈幕" + i,
"https://pic.818today.com/imgsy/image/2016/0215/6359114592207963687677523.jpg"));
}
barrageview = (BarrageView) findViewById(R.id.barrageview);
barrageview.setSentenceList(date);
}
}
4、彈幕控制項 BarrageView.java:核心在於用 Handler 接收訊息後動態 inflate 一個 item 佈局,透過 ObjectAnimator 讓它從右向左平移,並在動畫結束時移除 View 以釋放資源。Y 軸位置則透過隨機演算法分配,並避免相鄰彈幕重疊。
public class BarrageView extends FrameLayout {
private static ArrayList<Barrage> date = new ArrayList<>();
private int nowIndex = 0;
private Bitmap nowBitmap;
int width;
int height;
float scale;
FrameLayout frameLayout;
FrameLayout.LayoutParams tvParams;
static boolean IS_START = false;
long alltime;
long starttime;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Barrage barrage = (Barrage) msg.getData().getSerializable("barrage");
final LinearLayout layout = (LinearLayout) LayoutInflater
.from(getContext()).inflate(R.layout.barrageview_item, null);
layout.setLayoutParams(tvParams);
layout.setY(getRamdomY()); // 隨機 Y 值
layout.setX(width + layout.getWidth());
TextView textView = (TextView) layout.findViewById(R.id.barrageview_item_tv);
textView.setText(barrage.getBarrageInfo());
NGNormalCircleImageView img =
(NGNormalCircleImageView) layout.findViewById(R.id.barriageview_item_img);
if (nowBitmap != null) {
img.setImageBitmap(nowBitmap);
}
frameLayout.addView(layout);
final ObjectAnimator anim = ObjectAnimator.ofFloat(layout, "translationX", -width);
anim.setDuration(10000);
anim.addListener(new Animator.AnimatorListener() {
@Override public void onAnimationStart(Animator animation) { }
@Override public void onAnimationEnd(Animator animation) {
anim.cancel();
layout.clearAnimation();
frameLayout.removeView(layout); // 及時銷毀,釋放資源
}
@Override public void onAnimationCancel(Animator animation) { }
@Override public void onAnimationRepeat(Animator animation) { }
});
anim.start();
}
};
// 透過 HttpURLConnection 從網路取得 Bitmap
public static Bitmap getBitmapFromUrl(String path) {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream inputStream = conn.getInputStream();
return BitmapFactory.decodeStream(inputStream);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
int lastY;
// 隨機取得 Y 軸位置,避免與上一條重合
private float getRamdomY() {
int tempY, rY, result = 0;
int nowY = (int) (Math.random() * 3);
switch (nowY) {
case 0:
nowY = avoidTheSameY(nowY, lastY);
tempY = height / 4 - 25;
rY = (int) (Math.random() * height / 4);
result = (rY >= height / 8) ? tempY + rY : tempY - rY + 50;
lastY = nowY;
break;
case 1:
nowY = avoidTheSameY(nowY, lastY);
tempY = height / 2 - 25;
rY = (int) (Math.random() * height / 4);
result = (rY >= height / 8) ? tempY + rY : tempY - rY;
lastY = nowY;
break;
case 2:
nowY = avoidTheSameY(nowY, lastY);
tempY = height * 3 / 4 - 25;
rY = (int) (Math.random() * height / 4);
result = (rY >= height / 8) ? tempY + rY - 50 : tempY - rY;
lastY = nowY;
break;
}
return result;
}
private int avoidTheSameY(int nowY, int lastY) {
if (nowY == lastY) nowY++;
if (nowY == 4) nowY = 0;
return nowY;
}
public BarrageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
width = getWidth();
height = getHeight();
init();
}
private void init() {
setTime(600000);
starttime = System.currentTimeMillis();
scale = this.getResources().getDisplayMetrics().density;
frameLayout = (FrameLayout) findViewById(R.id.barrageview);
tvParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT, 50);
if (IS_START) {
startBarrageView();
IS_START = false;
}
}
public void startBarrageView() {
new Thread() {
@Override
public void run() {
while ((System.currentTimeMillis() - starttime < alltime)
&& (nowIndex <= date.size() - 1)) {
try {
nowBitmap = getBitmapFromUrl(date.get(nowIndex).getBarrageUrl());
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putSerializable("barrage", date.get(nowIndex));
nowIndex++;
message.setData(bundle);
handler.sendMessage(message);
Thread.sleep((long) (Math.random() * 3000) + 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
public void setSentenceList(ArrayList<Barrage> date1) {
date = date1;
IS_START = true;
}
public void setTime(long time) {
alltime = time;
}
}
整體思路與開頭描述一致,但這只是一個比較簡陋的雛形,仍有大量可模組化擴充的空間。例如可自訂的影片時長、彈幕速率、字體顏色、排列方式等,都可以依需求進一步定制。
關於 Android Button 響應頁面跳轉的常見問題解析
在 Android 應用中,Button 的點擊事件通常有兩種寫法,本文將說明這兩種方式,並釐清初學者最常遇到的頁面跳轉錯誤。 一、兩種常見的監聽寫法 第一種是使用具名的
在 Android 2.3 模擬 Android 4.0 風格 EditText:九宮格背景與焦點狀態
讓舊版介面更接近新樣式Android 4.0 的輸入框有清楚的邊框與焦點回饋,若在較舊版本想呈現類似風格,可以直接借用系統內建的九宮格圖片,再用 selector 切換不
Android PopupWindow 彈出視窗的使用示範
PopupWindow 是一個可浮動在任何檢視之上的輕量容器,常用來做「點選後出現相簿/拍照」這類浮動選單,比 Dialog 更不會遮斷使用者操作。 執行效果 Ma
Android 實現圖片壓縮示例代碼
核心思想是通過 BitmapFactory.Options 來縮放圖片,關鍵用到了它的 inSampleSize 參數(采樣率)。 當 inSampleSize 為 1