У меня была такая же проблема с datalist, я динамически связываю, добавив EnableViewState = "false", успокоил сообщение об ошибке. Я полагаю, что если я привязываюсь программно, тогда элемент управления заполняется на каждом столбце назад, вид состояние не должно поддерживаться, если оно может или не может измениться при каждом обратном вызове, поэтому я динамически связываю его, lol.
Лучшие две библиотеки, которые я нашел в сети, находятся на github:
Надеюсь, что это поможет вам
Я столкнулся с той же проблемой и не нашел подходящего решения для моего дела, поэтому решил пойти другим путем. Я создал пользовательский класс drawable. В этом классе я создал 2 Paints для линии прогресса и фоновой линии (с некоторым большим штрихом). Прежде всего установите startAngle и sweepAngle в конструкторе:
mSweepAngle = 0;
mStartAngle = 270;
Вот метод onDraw этого класса:
@Override
public void draw(Canvas canvas) {
// draw background line
canvas.drawArc(mRectF, 0, 360, false, mPaintBackground);
// draw progress line
canvas.drawArc(mRectF, mStartAngle, mSweepAngle, false, mPaintProgress);
}
Итак, теперь все, что вам нужно сделать, backgorund of view, в фоновом изменении потока sweepAngle:
mSweepAngle += 360 / totalTimerTime // this is mStep
и непосредственно вызывать InvalidateSelf () с некоторым интервалом (например, каждые 1 секунду или чаще, если вы хотите добиться плавного изменения хода) на представлении, которое сделайте это возможным в качестве фона. Вот оно!
P.S. Я знаю, я знаю ... конечно, вы хотите еще немного кода. Итак, вот весь поток:
<View
android:id="@+id/timer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
mPaintProgress = new Paint();
mPaintProgress.setAntiAlias(true);
mPaintProgress.setStyle(Paint.Style.STROKE);
mPaintProgress.setStrokeWidth(widthProgress);
mPaintProgress.setStrokeCap(Paint.Cap.ROUND);
mPaintProgress.setColor(colorThatYouWant);
То же самое для красок backgroung (установите ширину немного больше, если хотите)
public void update() {
mSweepAngle += mStep;
invalidateSelf();
}
OurSuperDrawableClass superDrawable = new OurSuperDrawableClass();
YourTimerView.setBackgroundDrawable(superDrawable);
YourTimerView.post(new Runnable() {
@Override
public void run() {
// update progress view
superDrawable.update();
}
});
Вот оно! Наслаждайтесь прохладным индикатором хода. Вот скриншот результата, если вам слишком скучно от этого количества текста. [/g0]
Очень полезный lib для пользовательской строки выполнения в android.
В вашем файле макета
<com.lylc.widget.circularprogressbar.example.CircularProgressBar
android:id="@+id/mycustom_progressbar"
.
.
.
/>
и файле Java
CircularProgressBar progressBar = (CircularProgressBar) findViewById(R.id.mycustom_progressbar);
progressBar.setTitle("Circular Progress Bar");
Я бы создал новый класс представления и получил бы от существующего ProgressBar. Затем переопределите функцию onDraw. Вам нужно будет сделать прямые призывы рисования к холсту для этого, так как его таможня - комбинация drawText, drawArc и drawOval должна делать это - овал для внешнего кольца и пустых частей, а дуга для цветной по частям. Возможно, вам также придется переопределить onMeasure и onLayout. Затем в вашем xml ссылайтесь на это представление по имени класса, например, когда вы хотите его использовать.
Я решил этот классный пользовательский индикатор выполнения, создав пользовательский вид. Я превысил метод onDraw (), чтобы нарисовать круги, заполнить дугу и текст на холсте.
ниже - пользовательский индикатор выполнения
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import com.investorfinder.utils.UiUtils;
public class CustomProgressBar extends View {
private int max = 100;
private int progress;
private Path path = new Path();
int color = 0xff44C8E5;
private Paint paint;
private Paint mPaintProgress;
private RectF mRectF;
private Paint textPaint;
private String text = "0%";
private final Rect textBounds = new Rect();
private int centerY;
private int centerX;
private int swipeAndgle = 0;
public CustomProgressBar(Context context) {
super(context);
initUI();
}
public CustomProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
initUI();
}
public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initUI();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initUI();
}
private void initUI() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(UiUtils.dpToPx(getContext(), 1));
paint.setStyle(Paint.Style.STROKE);
paint.setColor(color);
mPaintProgress = new Paint();
mPaintProgress.setAntiAlias(true);
mPaintProgress.setStyle(Paint.Style.STROKE);
mPaintProgress.setStrokeWidth(UiUtils.dpToPx(getContext(), 9));
mPaintProgress.setColor(color);
textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setStyle(Paint.Style.FILL);
textPaint.setColor(color);
textPaint.setStrokeWidth(2);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int viewWidth = MeasureSpec.getSize(widthMeasureSpec);
int viewHeight = MeasureSpec.getSize(heightMeasureSpec);
int radius = (Math.min(viewWidth, viewHeight) - UiUtils.dpToPx(getContext(), 2)) / 2;
path.reset();
centerX = viewWidth / 2;
centerY = viewHeight / 2;
path.addCircle(centerX, centerY, radius, Path.Direction.CW);
int smallCirclRadius = radius - UiUtils.dpToPx(getContext(), 7);
path.addCircle(centerX, centerY, smallCirclRadius, Path.Direction.CW);
smallCirclRadius += UiUtils.dpToPx(getContext(), 4);
mRectF = new RectF(centerX - smallCirclRadius, centerY - smallCirclRadius, centerX + smallCirclRadius, centerY + smallCirclRadius);
textPaint.setTextSize(radius * 0.5f);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(path, paint);
canvas.drawArc(mRectF, 270, swipeAndgle, false, mPaintProgress);
drawTextCentred(canvas);
}
public void drawTextCentred(Canvas canvas) {
textPaint.getTextBounds(text, 0, text.length(), textBounds);
canvas.drawText(text, centerX - textBounds.exactCenterX(), centerY - textBounds.exactCenterY(), textPaint);
}
public void setMax(int max) {
this.max = max;
}
public void setProgress(int progress) {
this.progress = progress;
int percentage = progress * 100 / max;
swipeAndgle = percentage * 360 / 100;
text = percentage + "%";
invalidate();
}
public void setColor(int color) {
this.color = color;
}
}
В макете XML
<com.your.package.name.CustomProgressBar
android:id="@+id/progress_bar"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentRight="true"
android:layout_below="@+id/txt_title"
android:layout_marginRight="15dp" />
в активности
CustomProgressBar progressBar = (CustomProgressBar)findViewById(R.id.progress_bar);
progressBar.setMax(9);
progressBar.setProgress(5);
[/g1]
Шаг 01 Вы должны создайте xml-файл в выпадающем файле, чтобы настроить внешний вид индикатора выполнения. Итак, я создаю свой файл xml как circle_progress_bar.xml.
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="120"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="140">
<item android:id="@android:id/background">
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:useLevel="false"
android:angle="0"
android:type="sweep"
android:thicknessRatio="50.0">
<solid android:color="#000000"/>
</shape>
</item>
<item android:id="@android:id/progress">
<rotate
android:fromDegrees="120"
android:toDegrees="120">
<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:angle="0"
android:type="sweep"
android:thicknessRatio="50.0">
<solid android:color="#ffffff"/>
</shape>
</rotate>
</item>
</layer-list>
Шаг 02 Затем создайте индикатор выполнения в вашем xml-файле Затем укажите имя xml-файла в вашей выпадающей папке как часть android: progressDrawable
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginLeft="0dp"
android:layout_centerHorizontal="true"
android:indeterminate="false"
android:max="100"
android:progressDrawable="@drawable/circular_progress_bar" />
Шаг 03 Визуализируйте индикатор выполнения с помощью потока
package com.example.progress;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
private ProgressBar progBar;
private TextView text;
private Handler mHandler = new Handler();
private int mProgressStatus=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progBar= (ProgressBar)findViewById(R.id.progressBar);
text = (TextView)findViewById(R.id.textView1);
dosomething();
}
public void dosomething() {
new Thread(new Runnable() {
public void run() {
final int presentage=0;
while (mProgressStatus < 63) {
mProgressStatus += 1;
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
progBar.setProgress(mProgressStatus);
text.setText(""+mProgressStatus+"%");
}
});
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
Попробуйте этот фрагмент кода, чтобы создать круговой индикатор выполнения (круговая диаграмма). передайте его целочисленное значение, чтобы нарисовать, сколько процентов площади заполнения. :)
private void circularImageBar(ImageView iv2, int i) {
Bitmap b = Bitmap.createBitmap(300, 300,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(b);
Paint paint = new Paint();
paint.setColor(Color.parseColor("#c4c4c4"));
paint.setStrokeWidth(10);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(150, 150, 140, paint);
paint.setColor(Color.parseColor("#FFDB4C"));
paint.setStrokeWidth(10);
paint.setStyle(Paint.Style.FILL);
final RectF oval = new RectF();
paint.setStyle(Paint.Style.STROKE);
oval.set(10,10,290,290);
canvas.drawArc(oval, 270, ((i*360)/100), false, paint);
paint.setStrokeWidth(0);
paint.setTextAlign(Align.CENTER);
paint.setColor(Color.parseColor("#8E8E93"));
paint.setTextSize(140);
canvas.drawText(""+i, 150, 150+(paint.getTextSize()/3), paint);
iv2.setImageBitmap(b);
}