自定义视图不会添加到预定义的XML布局中

时间:2013-04-07 19:01:04

标签: android android-layout

我要做的是将自定义视图添加到相对布局中。并且该相对布局是另一个线性布局的子元素。一切都工作正常,除了自定义视图没有显示它应该具有的位置。

自定义视图代码:

public class DrawView extends View {

private Path path = new Path();
private Paint paint = new Paint();

public DrawView(Context context, AttributeSet attrs) {
    super(context, attrs);

    paint.setAntiAlias(true);
    paint.setStrokeWidth(2.2f);
    paint.setColor(Color.WHITE);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeJoin(Paint.Join.ROUND);


}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawPath(path, paint);

}

@Override
public boolean onTouchEvent(MotionEvent event) {
    float eX = event.getX();
    float eY = event.getY();

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        path.moveTo(eX, eY);
        return true;
    case MotionEvent.ACTION_MOVE:
        path.lineTo(eX, eY);
        return true;
    case MotionEvent.ACTION_UP:
        break;
    default:
        return false;
    }
    invalidate();
    return true;
}

}

XML布局(线性和相对):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F24738"
android:orientation="vertical" >
<RelativeLayout
    android:id="@+id/draw_container"
    android:layout_width="match_parent"
    android:layout_height="450dp"
    android:background="#FFFFFF">
</RelativeLayout>

这是主要的活动:

public class DrawActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_draw);

    final RelativeLayout parentLayout = (RelativeLayout) findViewById(R.id.draw_container);
    parentLayout.addView(new DrawView(this, null));
}

}

当我尝试:

setContentView(new DrawView(this, null));

一切正常。我被打到了这里。我知道,我错过了很简单的事情。

1 个答案:

答案 0 :(得分:2)

您的代码正常运行,但您在白色背景上绘制了白色笔触。

尝试更改此行.-

paint.setColor(Color.WHITE);

paint.setColor(Color.RED);