如何在布局文件中定义Android GraphView?

时间:2012-12-21 15:07:58

标签: android graph

适用于Android的

GraphView库有一个GraphView类,它是一个用于创建图形的视图。这个抽象类扩展了LinearLayout,因此您可以通过嵌套LinearLayouts在布局中包含图形,如下所示:

xml layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:id="@+id/mainLayout">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
    <LinearLayout
        android:id="@+id/subLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />       
</LinearLayout>

MainActivity.java:

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        GraphViewData[] data = new GraphViewData[num];
        double v = 0;
        for (int i = 0; i < 10; i++) {
            v += 0.1;
            data[i] = new GraphViewData(i, Math.sin(v));            
        }
        GraphViewSeries seriesSin = new GraphViewSeries("Sinus", null, data);  
        GraphView graphView = new LineGraphView(this, "DemoGraphView");
        graphView.addSeries(seriesSin);
        graphView.setViewPort(2, 10);

        LinearLayout layout = (LinearLayout) findViewById(R.id.subLayout);  
        layout.addView(graphView);        
    }
}

我现在嵌套LinearLayouts但是也许有更好的方法在布局文件中包含图形,例如。就像你放置TextView或Button视图一样?

2 个答案:

答案 0 :(得分:2)

我认为你可以删除你的subLayout并将GraphView直接添加到mainLayout。所以你会保存一个布局。

答案 1 :(得分:1)

subLayout需要具有GraphView的固定高度:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/subLayout"
android:layout_width="fill_parent"
android:layout_height="250dip"
android:orientation="vertical" /> 

请参阅: https://github.com/jjoe64/GraphView-Demos/blob/master/res/layout/graphs.xml