Umayr
Umayr

Reputation: 933

Custom View doesn't add into a Predefined XML Layout

What I'm trying to do is to add a custom view into a relative layout. And that relative layout is the child of another Linear layout. Everything is working fine except custom view doesn't show up where it should have.

Custom View Code :

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 Layout (Linear and Relative) :

<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>

And that's the main Activity:

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));
}

}

When I try:

setContentView(new DrawView(this, null));

Everything works fine. I'm struck here. I know, I'm missing something very simple.

Upvotes: 1

Views: 271

Answers (1)

ssantos
ssantos

Reputation: 16526

Your code is working, but you're drawing white strokes on top of a white background.

try changing this line.-

paint.setColor(Color.WHITE);

for

paint.setColor(Color.RED);

Upvotes: 2

Related Questions