问题描述
我想通过 Java 代码动态创建一些视图并存储该视图以供进一步使用。但我不知道该怎么做,也找不到任何文档。
解决方法
一种简单的方法是在 android studio 中创建自定义类及其布局,并在您需要时通过在您的布局中调用它来使用它!这是自定义进度条的简单类 脚步 1.创建类并将其扩展到View
package com.habie.eri_youth.Habie_ProgressBars;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import com.habie.eri_youth.R;
/**
* Created by haben fesshaye on 08-03-2019.
*/
public class CircleArcProgress extends View {
private Paint paint=new Paint();
private int startAngle=120;
private int startAngle2=240;
private RectF oval=new RectF();
private int sweepAngle=100;
private float in_rad;
private float out_rad;
private int colorArc;
private int colorArc2;
public CircleArcProgress(Context context,AttributeSet attrs) {
super(context,attrs);
paint.setStyle(Paint.Style.STROKE);
TypedArray array=context.getTheme().obtainStyledAttributes(attrs,R.styleable.CircleArcProgress,0);
try{
in_rad=array.getDimension(R.styleable.CircleArcProgress_circle_size,50);
colorArc=array.getColor(R.styleable.CircleArcProgress_color_circle,Color.parseColor("#5C6BC0"));
out_rad=array.getDimension(R.styleable.CircleArcProgress_arc_radius,70);
colorArc2=array.getColor(R.styleable.CircleArcProgress_arc_color,Color.parseColor("#1A237E"));
}
catch (Exception e){
e.printStackTrace();
}
finally {
array.recycle();
}
post(animator);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
paint.setColor(colorArc);
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(getWidth()/2,getHeight()/2,in_rad,paint);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(colorArc2);
paint.setStrokeWidth(10);
oval.set(getWidth()/2-out_rad,getHeight()/2-out_rad,getWidth()/2+out_rad,getHeight()/2+out_rad);
canvas.drawArc(oval,startAngle2,sweepAngle,false,paint);
}
Runnable animator=new Runnable() {
@Override
public void run() {
if(startAngle2>=1){
startAngle2-=15;
}
else{
startAngle2=360;
}
invalidate();
postDelayed(this,30);
}
};
}
这是一个制作圆形进度条的简单类! 第 2 步描述有关在 res/value/attr 文件中创建的新视图的一些属性!像这样
<declare-styleable name="CircleArcProgress">
<attr name="circle_size" format="dimension"/>
<attr name="color_circle" format="color"/>
<attr name="arc_radius" format="dimension"/>
<attr name="arc_color" format="color"/>
</declare-styleable>
第 3 步 在你的布局中调用这个类,如下
<com.habie.eri_youth.Habie_ProgressBars.CircleArcProgress
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="@+id/progress"
app:dots_color="#0475f5"
android:visibility="visible"
/>
通过这样做,您可以通过导入在任何项目上使用此进度条! 希望这能给一些想法......