1

我正在使用以下代码将 agraph 类生成的图形加载到 R.id.TranFrag 容器中。但执行时不显示任何内容。请帮忙

Agraph agraph = new Agraph(getActivity(),30);
LinearLayout mainContainer = (LinearLayout) getActivity().findViewById(R.id.TranFrag);
mainContainer.addView(agraph);

其中 Agraph.java 如下

package com.salgaonkar.roomies_v3;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

public class Agraph extends View {
private Paint paint;
private float MaxY = 20; 
float horstart = 0;
public Agraph(Context context , float MaxY) {
    super(context);     
    paint = new Paint();
    this.MaxY = MaxY;
    setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    // TODO Auto-generated constructor stub
}
protected void onDraw(Canvas canvas) {
    float Height = getHeight()-20;
    float Width = getWidth();
    canvas.drawARGB(255, 255, 255, 255);
    for (int i=0; i<=10; i++) {     
        paint.setStrokeWidth(2);
        paint.setColor(Color.BLACK);
        paint.setTextAlign(Paint.Align.LEFT);
        paint.setTextSize(20.0f);
        float y = ((Height / 10) * i)+20;
        Log.d("y: ",""+y);
        Log.d("lable", ""+(MaxY)*(10-i)/10);
        canvas.drawText(String.valueOf((MaxY)*(10-i)/10),0,y,paint);
    }
}

}
4

3 回答 3

0

似乎视图 Agraph 没有实现 onMeasure(int, int) 方法。尝试添加类似的内容:

@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

setMeasuredDimension(100, 100);

}
于 2012-10-27T11:20:56.013 回答
0
Agraph agraph = new Agraph(getActivity(),30);
            LinearLayout mainContainer = (LinearLayout) getActivity().findViewById(R.id.TranFrag);
            mainContainer.addView(agraph);

好的,现在我在上面的代码中发现了错误,实际上它在容器中添加了视图,但由于容器已经存在,所以它不可见

填充了 ListView 所以我像这样更改代码

Agraph agraph = new Agraph(getActivity(),30);
            LinearLayout mainContainer = (LinearLayout) getActivity().findViewById(R.id.TranFrag); 
            mainContainer.removeAllViews(); //added
            mainContainer.addView(agraph);

现在它工作正常。

于 2012-10-27T14:21:43.293 回答
0

好的,我创建了一个示例项目,现在我正在调用片段活动并将主要活动上下文作为参数传递,并在片段中创建一个调用 Agraph 的构造函数并添加视图。活动中

Fragment f = new TestFragment(this);

并在片段中

public TestFragment(FExampleActivity fExampleActivity) {
    Agraph agraph = new Agraph(fExampleActivity,30);
    LinearLayout mainContainer = (LinearLayout)fExampleActivity.findViewById(R.id.frags);
    mainContainer.addView(agraph);
}

这对我有用..,

于 2012-10-27T11:51:15.860 回答