2010-12-20 164 views
2

我创建了以下代码以使用Canvas创建条形图和饼图。如何将视图添加到Android中的滚动视图?

这里是我的代码

public class ChartDemo extends Activity { 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    //ScrollView sv = new ScrollView(this); 

    LinearLayout llay = new LinearLayout(this); 
    llay.setOrientation(LinearLayout.VERTICAL); 

    float[] values = { 50, 100, 50, 20, 30, 60, 100, 90 }; 

    // Bar Chart 
    BarGraph BarChart = new BarGraph(this, values); 
    llay.addView(BarChart); 

    //Pie Chart 
    PieChartView Pie = new PieChartView(this, values); 
    llay.addView(Pie); 

    //sv.addView(llay); 

    setContentView(llay); 
    //setContentView(sv); 
    } 
} 

上面的代码只显示条形图。 我改变如下代码它给人的黑色(空白)屏幕only.With出任何错误和异常

public class ChartDemo extends Activity { 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    ScrollView sv = new ScrollView(this); 

    LinearLayout llay = new LinearLayout(this); 
    llay.setOrientation(LinearLayout.VERTICAL); 

    float[] values = { 50, 100, 50, 20, 30, 60, 100, 90 }; 

    // Bar Chart 
    BarGraph BarChart = new BarGraph(this, values); 
    llay.addView(BarChart); 

    //Pie Chart 
    PieChartView Pie = new PieChartView(this, values); 
    llay.addView(Pie); 

    sv.addView(llay); 

    setContentView(sv); 
    } 
} 

而创建我的图表视图像下面

public class PieChartView extends View { 

private float[] Values; 

public PieChartView(Context context, float[] Values) { 
    super(context); 

    this.Values = Values; 

} 

protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 

       ....... 
       ......... 

     } 


} 

我需要使用滚动查看在单一屏幕中添加图表。但我无法在单个Activity中添加Both。怎么做?

+0

您能详细说明一下您的意思是“不能够”吗?你是否有一些错误,或者他们没有正确显示? – Juhani 2010-12-20 11:52:13

+0

当我将LinearLayout添加到ScrollView时,我得到了黑屏只有sv.addView(llay); setContentView(sv); – 2010-12-20 12:22:13

回答

4

当你添加编程看待一些布局,像的LinearLayout或滚动型(从FrameLayout里派生),你应该对你的看法设置布局参数,像这样(只是一个例子):

BarGraph BarChart = new BarGraph(this, values); 
// be sure to use correct layout params for your layout 
LinearLayout.LayoutParams llp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
llp.weight = 1.0f; 
BarChart.setLayoutParams(llp); 
llay.addView(BarChart); 

FrameLayout.LayoutParams flp = new /* ... */; 
llay.setLayoutParams(flp); 

sv.addView(llay); 

如果你不会设置它们,它们会根据布局获取默认值,并且可能会根据添加的视图来完成这项工作。 (顺便说一句,在Java变量名称以小写字母开头)

相关问题