自定義Progress小控制項

来源:http://www.cnblogs.com/LiuZhen/archive/2017/07/10/7145645.html
-Advertisement-
Play Games

progress各種各樣的都有,自定義大多數也是簡單的,根據業務需求來自己定義,記錄一下,先上效果圖 本來想找個第三方改改就上的,不過自己的業務需求有點不搭,一下子沒找到合適的,也沒這麼多時間去找了,想想還是自己寫個吧,因為也簡單 主要就是需求就是橢圓進度,百分比跟隨漸變背景,這樣一想其實就是一個布 ...


progress各種各樣的都有,自定義大多數也是簡單的,根據業務需求來自己定義,記錄一下,先上效果圖

本來想找個第三方改改就上的,不過自己的業務需求有點不搭,一下子沒找到合適的,也沒這麼多時間去找了,想想還是自己寫個吧,因為也簡單

主要就是需求就是橢圓進度,百分比跟隨漸變背景,這樣一想其實就是一個佈局,然後控制裡面的進度長度,或者移動,我這是控制長度,這樣畢竟簡單,而且擴展好,以後進度條有什麼奇葩需求也好改

  1 import android.content.Context;
  2 import android.content.res.TypedArray;
  3 import android.graphics.Color;
  4 import android.support.annotation.AttrRes;
  5 import android.support.annotation.NonNull;
  6 import android.support.annotation.Nullable;
  7 import android.util.AttributeSet;
  8 import android.view.Gravity;
  9 import android.view.View;
 10 import android.view.ViewGroup;
 11 import android.widget.FrameLayout;
 12 import android.widget.TextView;
 13 
 14 import com.app.commonlibrary.R;
 15 
 16 /**
 17  * Created by LiuZhen on 2017/7/8.
 18  */
 19 
 20 public class UpdateProgressBar extends FrameLayout {
 21 
 22     private TextView tv_progress;
 23     private int width;
 24     private ViewGroup.LayoutParams params;
 25     /**
 26      * The progress text offset.
 27      */
 28     private int mOffset;
 29     /**
 30      * The progress text size.
 31      */
 32     private float mTextSize;
 33     /**
 34      * The progress text color.
 35      */
 36     private int mTextColor;
 37     private float default_text_size;
 38     /**
 39      * The progress area bar color.
 40      */
 41     private int mReachedBarColor;
 42     /**
 43      * The bar unreached area color.
 44      */
 45     private int mUnreachedBarColor;
 46     private final int default_reached_color = Color.rgb(66, 145, 241);
 47     private final int default_unreached_color = Color.rgb(204, 204, 204);
 48     private final int default_text_color = Color.rgb(66, 145, 241);
 49 
 50     public UpdateProgressBar(@NonNull Context context) {
 51         this(context,null);
 52     }
 53 
 54     public UpdateProgressBar(@NonNull Context context, @Nullable AttributeSet attrs) {
 55         this(context, attrs,0);
 56     }
 57 
 58     public UpdateProgressBar(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
 59         super(context, attrs, defStyleAttr);
 60         init(attrs, defStyleAttr);
 61     }
 62 
 63     @Override
 64     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
 65 
 66         int desiredWidth = 100;
 67         int desiredHeight = 100;
 68 
 69         int widthMode = MeasureSpec.getMode(widthMeasureSpec);
 70         int widthSize = MeasureSpec.getSize(widthMeasureSpec);
 71         int heightMode = MeasureSpec.getMode(heightMeasureSpec);
 72         int heightSize = MeasureSpec.getSize(heightMeasureSpec);
 73 
 74         int height;
 75 
 76         //Measure Width
 77         if (widthMode == MeasureSpec.EXACTLY) {
 78             //Must be this size
 79             width = widthSize;
 80         } else if (widthMode == MeasureSpec.AT_MOST) {
 81             //Can't be bigger than...
 82             width = Math.min(desiredWidth, widthSize);
 83         } else {
 84             //Be whatever you want
 85             width = desiredWidth;
 86         }
 87 
 88         //Measure Height
 89         if (heightMode == MeasureSpec.EXACTLY) {
 90             //Must be this size
 91             height = heightSize;
 92         } else if (heightMode == MeasureSpec.AT_MOST) {
 93             //Can't be bigger than...
 94             height = Math.min(desiredHeight, heightSize);
 95         } else {
 96             //Be whatever you want
 97             height = desiredHeight;
 98         }
 99 
100         int childCount = getChildCount();
101         for (int i = 0; i < childCount; i++) {
102             View child = getChildAt(i);
103             ViewGroup.LayoutParams lp = child.getLayoutParams();
104             int childWidthSpec = getChildMeasureSpec(widthMeasureSpec, 0, lp.width);
105             int childHeightSpec = getChildMeasureSpec(heightMeasureSpec, 0, lp.height);
106             child.measure(childWidthSpec, childHeightSpec);
107         }
108         params = tv_progress.getLayoutParams();
109         params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
110         params.height = ViewGroup.LayoutParams.MATCH_PARENT;
111         tv_progress.setLayoutParams(params);
112         height = tv_progress.getMeasuredHeight();
113         //MUST CALL THIS
114         setMeasuredDimension(width, height);
115     }
116 
117 
118     private void init(AttributeSet attrs, int defStyleAttr){
119 
120         default_text_size = 8;
121         //load styled attributes.
122         final TypedArray attributes = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.UpdateProgressBar,
123                 defStyleAttr, 0);
124 
125         mTextSize = attributes.getDimension(R.styleable.UpdateProgressBar_update_text_size, default_text_size);
126         mReachedBarColor = attributes.getResourceId(R.styleable.UpdateProgressBar_update_reached_color, default_reached_color);
127         mUnreachedBarColor = attributes.getResourceId(R.styleable.UpdateProgressBar_update_unreached_color, default_unreached_color);
128         mTextColor = attributes.getColor(R.styleable.UpdateProgressBar_update_text_color, default_text_color);
129 
130         setDefaultProgressBar();
131 
132         mOffset = px2dip(3);
133 
134         attributes.recycle();
135     }
136 
137     private void setDefaultProgressBar(){
138         setBackgroundResource(mUnreachedBarColor);
139         tv_progress = new TextView(getContext());
140         tv_progress.setTextSize(mTextSize);
141         tv_progress.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
142         tv_progress.setTextColor(mTextColor);
143         tv_progress.setLines(1);
144         tv_progress.setBackgroundResource(mReachedBarColor);
145         tv_progress.setPadding(dip2px(4),0,dip2px(8),0);
146         tv_progress.setText("0 %");
147         addView(tv_progress);
148     }
149 
150     public void setProgress(int progress){
151         tv_progress.setText(progress+"%");
152         int proWidth = width*progress/100;
153         if (tv_progress.getMeasuredWidth() < proWidth) {
154             //這裡不能填充mOffset,因為是橢圓進度條,填充會導致橢圓寬度被進度條覆蓋,導致不美觀
155 //            tv_progress.setLayoutParams(params);
156             tv_progress.setWidth(proWidth);
157         }
158     }
159 
160     /**
161      * 根據手機的解析度從 dp 的單位 轉成為 px(像素)
162      */
163     public int dip2px(float dpValue) {
164         final float scale = getContext().getResources().getDisplayMetrics().density;
165         return (int) (dpValue * scale + 0.5f);
166     }
167 
168     /**
169      * 根據手機的解析度從 px(像素) 的單位 轉成為 dp
170      */
171     public int px2dip(float pxValue) {
172         final float scale = getContext().getResources().getDisplayMetrics().density;
173         return (int) (pxValue / scale + 0.5f);
174     }
175 
176     /**
177      * 將px值轉換為sp值,保證文字大小不變
178      */
179     public int px2sp(float pxValue) {
180         final float fontScale = getContext().getResources().getDisplayMetrics().scaledDensity;
181         return (int) (pxValue / fontScale + 0.5f);
182     }
183 
184     /**
185      * 將sp值轉換為px值,保證文字大小不變
186      */
187     public int sp2px(float spValue) {
188         final float fontScale = getContext().getResources().getDisplayMetrics().scaledDensity;
189         return (int) (spValue * fontScale + 0.5f);
190     }
191 
192 }
UpdateProgressBar

 

用法佈局文件

1 <com.progressbar.example.UpdateProgressBar
2         xmlns:pro="http://schemas.android.com/apk/res-auto"
3         android:id="@+id/progress"
4         android:layout_width="match_parent"
5         android:layout_height="wrap_content"
6         pro:update_text_size="6sp"
7         pro:update_text_color="#FFFFFF"
8         pro:update_unreached_color="@drawable/shape_corner_progressbg"
9         pro:update_reached_color="@drawable/shape_corner_progressbar"/>
 1 import android.os.Bundle;
 2 import android.support.v7.app.ActionBarActivity;
 3 import android.support.v7.app.AppCompatActivity;
 4 import android.view.Menu;
 5 import android.view.MenuItem;
 6 import android.widget.Toast;
 7 
 8 import com.progressbar.NumberProgressBar;
 9 
10 import java.util.Timer;
11 import java.util.TimerTask;
12 
13 
14 public class MainActivity extends AppCompatActivity {
15     private Timer timer;
16     private UpdateProgressBar progressBar;
17     private int progress;
18 
19     @Override
20     protected void onCreate(Bundle savedInstanceState) {
21         super.onCreate(savedInstanceState);
22         setContentView(R.layout.activity_main);
23         progressBar = (UpdateProgressBar)findViewById(R.id.progress);
24 
25         timer = new Timer();
26         timer.schedule(new TimerTask() {
27             @Override
28             public void run() {
29                 runOnUiThread(new Runnable() {
30                     @Override
31                     public void run() {
32                         progress++;
33                         progressBar.setProgress(progress);
34                         if(progress == 100) {
35                             Toast.makeText(getApplicationContext(), getString(R.string.finish), Toast.LENGTH_SHORT).show();
36 //                            progress = 0;
37 //                            progressBar.setProgress(0);
38                             timer.cancel();
39                         }
40                     }
41                 });
42             }
43         }, 1000, 100);
44     }
45 
46     @Override
47     public boolean onCreateOptionsMenu(Menu menu) {
48         // Inflate the menu; this adds items to the action bar if it is present.
49         getMenuInflater().inflate(R.menu.main, menu);
50         return true;
51     }
52 
53     @Override
54     public boolean onOptionsItemSelected(MenuItem item) {
55         // Handle action bar item clicks here. The action bar will
56         // automatically handle clicks on the Home/Up button, so long
57         // as you specify a parent activity in AndroidManifest.xml.
58         int id = item.getItemId();
59         if (id == R.id.action_settings) {
60             return true;
61         }
62         return super.onOptionsItemSelected(item);
63     }
64 
65     @Override
66     protected void onDestroy() {
67         super.onDestroy();
68         timer.cancel();
69     }
70 }
MainActivity

漸變背景

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <shape xmlns:android="http://schemas.android.com/apk/res/android">
 3 
 4     <solid android:color="#4984f2"/>
 5 
 6     <gradient
 7         android:startColor="#4984f2"
 8         android:endColor="#000" />
 9 
10     <corners
11         android:topLeftRadius="15dp"
12         android:topRightRadius="15dp"
13         android:bottomLeftRadius="15dp"
14         android:bottomRightRadius="15dp"/>
15 </shape>
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <shape xmlns:android="http://schemas.android.com/apk/res/android">
 3 
 4     <solid android:color="#dadada"/>
 5 
 6     <gradient
 7     android:startColor="#FFF"
 8     android:endColor="#000" />
 9 
10 
11     <corners
12         android:topLeftRadius="15dp"
13         android:topRightRadius="15dp"
14         android:bottomLeftRadius="15dp"
15         android:bottomRightRadius="15dp"/>
16 </shape>

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 隨著商業化競爭激烈程度不斷增大,決定一個產品能否成功的關鍵有兩點:一是過硬的質量和性能,二是優秀的“顏值”與體驗。UI/UX設計師的重要工作就是為產品設計絕世美顏,優化產品的交互性能,從而給用戶帶來良好的體驗。所以,想要成為一名優秀的UI/UX設計師,需要掌握的不僅僅是繪圖,設計,在這裡我們一起分享 ...
  • 前兩天從一個網站中看到了一些比較好的loading動畫效果,是用純CSS3來寫的,感覺不錯,就嘗試著照著效果來自己寫出來。 在開始之前,先複習一個小知識:CSS3新增的關鍵幀動畫,可以用來實現很多的動畫,我們可以通過animation-delay來控制動畫延遲執行,來實現豐富的效果。 當animat ...
  • 覽網站的時候,有些網站總是在右下角,左上角或者其他地方投放廣告。 我用jQuery試著自己做了一個,代碼如下,如有不對的地方請各位不吝賜教 效果圖如下 關於這個效果,我有以下思索: 1.可以添加一個計時器,倒計時‘還有5S關閉’,還有‘4S關閉’,告訴用戶這個廣告只是臨時投放,5S後自動關閉,這個可 ...
  • 自從HTML5誕生之後,就是開始建立了一個標準的原則,那就是所有的技術它必須是面向開放,並不能有專利的一個存在,在整個期間Opera捐獻了css技術,而google的話則是給開發者提供了視頻的webM,本文將帶大家來看看html5它是如何帶來全新的網路格局的,感興趣的朋友們可以關註一下,為開發而做準 ...
  • 前言:最近在做一個日期選擇功能,在日期轉換的時候經常換到暈,總結一下常用的Date對象的相關用法,方便日後直接查看使用~ 1. new Date()的使用方法有: 不接收任何參數:返回當前時間; 接收一個參數x: 返回1970年1月1日 + x毫秒的值。 new Date(1, 1, 1)返回190 ...
  • 在Vue中,我們平時數據驅動視圖時候,內部自帶的指令有時候解決不了一些需求,這時候,Vue給我們一個很好用的東東 directive 這個單詞是我們寫自定義指令的關鍵字哦 之定義指令為我們提供了幾個鉤子函數,這時候你一定好奇什麼是鉤子函數,說簡單點,就是集中表現狀態 bind: 只調用一次,指令第一 ...
  • // select only the first element for each name, and only those with rules specified //if ( this.name in rulesCache || !validator.objectLength($(this). ...
  • 上次我們提到用vue實現過渡動畫,其實只講了vue動畫的一部分,用vue自帶的css狀態控制動畫實現,不帶js http://www.cnblogs.com/null11/p/7081506.html 在vue中,還有一種方式控制動畫的實現,那就是用js控制動畫的狀態 分別是下麵3種狀態 :befo ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...