今天接到了产品同学的一个需求,要显示带气泡的进度条,花一上午实现了需求:
布局文件中定义一个进度条:

1
2
3
4
5
6
7
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="200dp"
android:layout_height="20dp"
android:progressDrawable="@drawable/progress_bar_color"
android:visibility="gone" />

bubble_layout.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bubble_background"
android:orientation="vertical"
android:padding="10dp">

<TextView
android:id="@+id/tvProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0%"
android:textSize="18sp"
android:textColor="#ffffff"/>
</LinearLayout>

气泡窗口的背景drawable

1
2
3
4
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#44000000"/>
<corners android:radius="5dp"/>
</shape>

进度条颜色:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<solid android:color="#dddddd"/>
</shape>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<solid android:color="#00ff00"/>
</shape>
</clip>
</item>
</layer-list>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
ProgressBar progressBar = findViewById(R.id.progressBar);

// 显示气泡窗口
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View bubbleLayout = inflater.inflate(R.layout.bubble_layout, null);
TextView tvProgress = bubbleLayout.findViewById(R.id.tvProgress);

final PopupWindow popupWindow = new PopupWindow(bubbleLayout, 200, 100, true);
popupWindow.setBackgroundDrawable(new BitmapDrawable());

// 设置气泡位置
int[] location = new int[2];
progressBar.getLocationOnScreen(location);
int x = location[0] + progressBar.getWidth() / 2 - bubbleLayout.getWidth() / 2;
int y = location[1] - popupWindow.getHeight();

popupWindow.showAtLocation(progressBar, Gravity.NO_GRAVITY, x, y);

// 更新气泡中的进度
progressBar.setProgress(50); // 假设进度为50%
tvProgress.setText("50%");

// 进度更新逻辑
progressBar.setOnProgressChangeListener((progress, max) -> {
int percent = (int) (((float) progress / (float) max) * 100);
tvProgress.setText(percent + "%");
if (percent >= 100) {
popupWindow.dismiss();
progressBar.setVisibility(View.GONE);
}
});