我正在尝试在 Fragment 内用 Canvas 画一条线。经过一些研究,我似乎只需要扩展 View 类并覆盖 onDraw,然后返回我通常会在其中膨胀布局的新 View 类的实例。但是,当我在设备上访问片段时,我看到的只是一个白屏。这是我到目前为止所拥有的:
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());
}
}
我在这里想念什么?
编辑:对于其他面临此问题的人,此代码结果可以正常工作。我只是在我的活动中显示它时遇到问题。