2010-12-20 203 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變量名稱以小寫字母開頭)

相關問題