首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android 自定義 TextView 實現進度條文字效果

     編輯:程式設計疑難解答

需求

TextView 顯示類似進度條的動態文字效果(如下載進度、倒計時)。

方案對比

方案優點缺點
SeekBar/ProgressBar + TextView 疊加原生組件、穩定、無需自定義繪製佈局稍複雜
自定義 View 繪製文字進度高度定制化、單一組件需處理文字測量、動畫、狀態保存
ObjectAnimator 動畫 TextView 文本代碼簡潔、Material 風格僅適用數字變化

推薦:SeekBar + TextView 組合

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:progressDrawable="@drawable/progress_bg"
        android:thumb="@null"/>

    <TextView
        android:id="@+id/tvProgress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="0%"
        android:textColor="#FFF"
        android:textSize="14sp"/>
</FrameLayout>
SeekBar seekBar = findViewById(R.id.seekBar);
TextView tv = findViewById(R.id.tvProgress);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    @Override public void onProgressChanged(SeekBar sb, int progress, boolean fromUser) {
        tv.setText(progress + "%");
    }
    @Override public void onStartTrackingTouch(SeekBar sb) {}
    @Override public void onStopTrackingTouch(SeekBar sb) {}
});

進階:帶動畫的數字增長

ObjectAnimator.ofInt(0, 100).setDuration(1000).addUpdateListener(anim -> {
    tv.setText(anim.getAnimatedValue() + "%");
}).start();
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved