【问题标题】:Custom progress bar not working in only Galaxy Nexus device自定义进度条仅在 Galaxy Nexus 设备中不起作用
【发布时间】:2012-11-19 10:50:22
【问题描述】:

我需要创建进度条,所以我通过扩展 ProgressBar 在 onDraw 方法中完成了它,并且此代码在所有 android 设备中运行,除了 Galaxy nexus .. 虽然它没有抛出和异常,但进度可绘制不是通过更新异步任务。这段代码在所有设备上完全可以工作,除了galaxy nexus

@Override
protected synchronized void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint textPaint = new Paint();
    textPaint.setAntiAlias(true);
    textPaint.setColor(textColor);

    Typeface tmTypeface = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
    textPaint.setTypeface(tmTypeface);
    textPaint.setTextSize(textSize * mContext.getResources().getDisplayMetrics().density);
    Rect bounds = new Rect();
    textPaint.getTextBounds(text, 0, text.length(), bounds);
    int x = getWidth() / 2 - bounds.centerX();
    int y = getHeight() / 2 - bounds.centerY();
    canvas.drawBitmap(thumbnailBitmap, 10, y - bitmapHeight / 2, null);
    canvas.drawText(text, 15 + thumbnailBitmap.getWidth(), y, textPaint);
    canvas.drawBitmap(downloadBitmap, getWidth() - bitmapWidth, y - bitmapHeight / 2, null);

}

问题可能与可绘制和样式有关,但它适用于所有版本和所有设备

【问题讨论】:

    标签: android progress-bar custom-component


    【解决方案1】:

    我在这段代码 sn-p 中看不到您在问题中陈述的问题,但我可以在您的代码本身中看到很多问题。

    我猜你正在继承View,我不知道你为什么synchronized onDraw 方法,没有必要这样做。通过将onDraw 方法设为synchronized,您只需在执行onDraw 时阻止所有其他线程访问您的对象,并注意onDraw 可能会被非常频繁地调用,如果您确实需要同步,请创建一个 small synchronized 阻止,如果这样做就足够了。

    还有一点,在每次调用onDraw 时创建一个新的PaintTypeface 确实是糟糕 的想法,它会破坏性能。将它们保存为实例变量并尽可能重用它们,即使是 Rect 对象也应该被重用。

    让我们回到你的问题,如果你想创建一个自定义进度条,你可以简单地创建一个进度条样式并在你的布局定义中引用(在 XML 中)。在drawable 目录下创建my_progressbar.xml 并将以下内容保存在文件中,在您的ProgressBar 定义中引用此样式,如<ProgressBar ... android:progressDrawable="@drawable/my_progressbar"/>

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
    <item android:id="@android:id/background">
        <shape android:shape="rectangle" >
            <solid android:color="#ffcccccc" />
        </shape>
    </item>
    
    <item android:id="@android:id/secondaryProgress">
        <clip>
        <shape android:shape="rectangle" >
            <solid android:color="#ff000000" />
        </shape>
        </clip>
    </item>
    
    <item android:id="@android:id/progress">
        <clip>
        <shape android:shape="rectangle" >
            <solid android:color="#ffff6100" />
        </shape>
        </clip>
    </item>
    

    查看this 了解有关定义形状的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-21
      • 2013-02-08
      • 2015-11-29
      • 1970-01-01
      • 1970-01-01
      • 2021-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多