我在绘制/布局期间获得3个对象分配警告
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
Paint textPaint = new Paint();
textPaint.setARGB(50,100,100,250);
textPaint.setTextAlign(Align.CENTER);
textPaint.setTextSize(50);
textPaint.setTypeface(font);
canvas.drawText("Logan is awesom",canvas.getWidth()/2,200,textPaint);
canvas.drawBitmap(pBall, (canvas.getWidth()/2), changingY, null);
if (changingY <canvas.getHeight()){
changingY += 10;
}else{
changingY=0;
}
Rect middleRect = new Rect();
middleRect.set(0, 400, canvas.getWidth(), 550);
Paint ourBlue = new Paint();
ourBlue.setColor(Color.BLUE);
canvas.drawRect(middleRect, ourBlue);
我得到一个错误的新Rect();和new Paint();
确切的错误是在绘制/布局操作期间避免对象分配(而不是预先定位和重用)
好吧,你的"错误"指出了确切的问题。onDraw()
方法被操作系统多次调用,因此在这个函数中分配一些东西是非常糟糕的主意。您需要事先分配您的Rect
和Paint
,并且只在onDraw
内使用它们
class YourClass extends View
{
Rect middleRect;
Paint ourBlue;
Paint textPaint;
public YourClass()
{
//constructor
init();
}
private void init()
{
middleRect = new Rect();
ourBlue; = new Paint();
textPaint = new Paint();
ourBlue.setColor(Color.BLUE);
textPaint.setARGB(50,100,100,250);
textPaint.setTextAlign(Align.CENTER);
textPaint.setTextSize(50);
textPaint.setTypeface(font);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
canvas.drawText("Logan is awesom",canvas.getWidth()/2,200,textPaint);
canvas.drawBitmap(pBall, (canvas.getWidth()/2), changingY, null);
if (changingY <canvas.getHeight()){
changingY += 10;
}else{
changingY=0;
}
//if canvas size doesn't change - this can be moved to init() as well
middleRect.set(0, 400, canvas.getWidth(), 550);
canvas.drawRect(middleRect, ourBlue);
}
}
对于我来说,我在布局中遇到了这个错误,特别是在使用显示度量时。
我已经使用了这个imageview:
<com.steve.thirdparty.ScalableImageView
android:id="@+id/iv_posted_img_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:background="@drawable/golive_load_image"
android:layout_below="@+id/tv_user_posted_msg_post_items_home"
android:contentDescription="@string/cont_desc"/>
ScalableImageView.java:
导入静态com.steve.TabHomeActivity.displaymetrics;
public class ScalableImageView extends ImageView {
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
}
我通过在Activity的onCreate()方法中添加静态DisplayMetrices解决了这个问题。
TabHomeActivity.java:
public static DisplayMetrics displaymetrics;
*inside onCreate()*
displaymetrics = new DisplayMetrics();
在绘制/布局操作中避免对象分配(预先定位和重用)
留言给你一个解决方案,所以我不明白你的问题是什么
你必须将新对象的创建移动到onCreate方法,所以它们只创建一次,然后在onDraw方法中使用它们。