如何在Android中的滚动视图中添加视图?

时间:2010-12-20 11:46:31

标签: android

我创建以下代码以使用Canvas创建条形图和饼图。

这是我的代码

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);
   }
 }

以上代码仅显示BarChart。 我更改了我的代码,如下所示,它只给出了黑色(空白)屏幕。没有错误和异常

  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。如何做到这一点?

1 个答案:

答案 0 :(得分:4)

当你以编程方式将视图添加到某些布局时,比如LinearLayout或ScrollView(派生自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变量名称中以小写字母开头)