Android扩展ViewGroup绘制图表

时间:2015-02-24 19:45:21

标签: android

您好我尝试创建自定义图表。所以我试试这样的smth。但我在屏幕上看不到任何东西。我做错了什么?谢谢你的帮助。我在构造函数中调用init fucntion。

public class HorizontalBarChart extends ViewGroup {

private void init(){
    textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    textPaint.setColor(0x000);
    rectPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    rectPaint.setColor(0xFF9C27B0);
    myTextView tt = new myTextView(getContext());
    addView(tt);
}

private class myTextView extends View{

    public myTextView(Context context) {
        super(context);
    }
    @Override
    protected void onDraw(Canvas canvas){
        canvas.drawRect(100,100, 100,100, rectPaint);
        canvas.drawText("PRIVET", 30, 30, textPaint);
    }
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {

}
}

在activity_main.xml

<smth.HorizontalBarChart
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/Pie"/>

1 个答案:

答案 0 :(得分:0)

可能会迟到,但这是我的评论,希望它有所帮助,因为我只是处理同样的问题

你应该告诉android在哪里绘制myTextView实例。 ......好像

public class HorizontalBarChart extends ViewGroup {

private myTextView mView;

/* also remember to override the constructor and call init() in it! */

 private void init(){
    textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    textPaint.setColor(0x000);
    rectPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    rectPaint.setColor(0xFF9C27B0);
    mView = new myTextView(getContext());
    addView(mView);
}

private class myTextView extends View{

    public myTextView(Context context) {
        super(context);
    }
    @Override
    protected void onDraw(Canvas canvas){
        canvas.drawRect(100,100, 100,100, rectPaint);
        canvas.drawText("PRIVET", 30, 30, textPaint);
    }
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
     mView.layout(l, t, r, b);

}
}

您可能还需要覆盖onMeasure, 我的建议:

  1. 你应该有一个令人信服的理由来覆盖viewGroup,你可以使用或扩展许多viewGroup,

  2. 只有一个视图,为什么要扩展ViewGroup,只需使用扩展视图。