I am trying to draw a line with Canvas inside of a Fragment. After some research it appeared that I just had to extend the View class and override onDraw, then return an instance of my new View class where I would normally inflate a layout. However when I access the fragment on my device all I see is a white screen. Here is what I have so far:
package com.example.testing;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LineTab extends Fragment
{
private class DrawView extends View {
Paint paint = new Paint();
public DrawView(Context context) {
super(context);
paint.setColor(Color.BLACK);
}
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setColor(Color.BLACK);
}
public DrawView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint.setColor(Color.BLACK);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(0, 0, 50, 50, paint);
canvas.drawLine(50, 0, 0, 50, paint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(parentWidth, parentHeight);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return new DrawView(this.getActivity());
}
}
What am I missing here?
EDIT: For anyone else facing this problem, this code turned out to work fine. I just had issues displaying it within my activity.