首页 > 技术文章 > 给progressbar设置drawable和自定义progressbar

sj-anhui 2019-07-01 21:56 原文

在项目中遇见给progressbar直接设置drawable背景不起效果,解决方法如下:

public class SetProgressDrawable {
    private Context context;
    private ProgressBar progressBar;
    private int resId;

    public SetProgressDrawable(Context context, ProgressBar progressBar, int resId) {
        this.context = context;
        this.progressBar = progressBar;
        this.resId = resId;
    }

    @SuppressLint("NewApi")
    public void setProgressDrawable(){
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
            progressBar.setProgressDrawableTiled(ContextCompat.getDrawable(context,resId));
        }else {
            Drawable layerDrawable = progressBar.getResources().getDrawable(resId);
            Drawable drawable = getMethod(progressBar, new Object[]{layerDrawable, false});
            progressBar.setProgressDrawable(drawable);
        }
    }

    private Drawable getMethod(Object object, Object[] paras) {
        Drawable newDrawable = null;
        try {
            Class<?>[] c = new Class[2];
            c[0] = Drawable.class;
            c[1] = boolean.class;
            String name = "tileify";
            @SuppressLint("PrivateApi")
            Method method = ProgressBar.class.getDeclaredMethod(name, c);
            method.setAccessible(true);
            newDrawable = (Drawable) method.invoke(object, paras);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return newDrawable;
    }
}

你可以这样用

推荐阅读