在绘制/布局
期间,我得到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()上遇到错误; 以及新的Paint();
确切的错误是在绘制/布局操作期间避免对象分配(预定位和重用)
答案 0 :(得分:22)
嗯,你的'错误'指的是确切的问题。操作系统多次调用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);
}
}
答案 1 :(得分:0)
对我来说,我在布局中遇到了这个错误,尤其是在使用显示矩阵时。
我使用过这张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:强>
import static 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();
答案 2 :(得分:-3)
在绘制/布局操作期间避免对象分配(预先定位并重新使用)
这条消息给你一个解决方案,所以我不明白你的问题是什么。
您必须将新对象的创建移动到onCreate方法,因此它们只创建一次,稍后在onDraw方法中使用它们。