如何在Android Fragment中使用achartengine返回带图表的布局

时间:2012-04-22 10:22:38

标签: android android-layout achartengine

我正在尝试使用图表和onCreateView片段中的一些按钮返回布局。我不知道如何将两个视图合二为一。我只能返回没有图表的图表或布局:

    public class ChartFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        // LineGraph - class which draws the graph using achartengine
        final LineGraph lineGraph = new LineGraph();
        final GraphicalView chart = lineGraph.getGraphicalView(inflater.getContext());
        final View view = inflater.inflate(R.layout.chart, container, false);


        Button drawChartButton = (Button) view.findViewById(R.id.button_draw_chart);

        drawChartButton.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // update chart for new data
            }
        });

        return chart; //return the chart only
        // return view; // return layout but without the chart

    }

}

在活动中使用以下代码:

 Button chartButton = (Button) findViewById(R.id.button_draw_chart);
    chartButton.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
        LineGraph lineGrpah = new LineGraph();

        GraphicalView testChart = lineGrpah
            .getGraphicalView(SimpleApp.this);
        layout.addView(testChart, new LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
            }
        });

和xml:

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical" >


   <LinearLayout
       android:id="@+id/chart"
       android:layout_width="600dp"
       android:layout_height="350dp"
       android:layout_margin="15dp" >

   </LinearLayout>

   <Button
       android:id="@+id/button_draw_chart"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/button_draw_chart" />

</LinearLayout>

工作正常,但我不知道如何在片段中执行此操作。

1 个答案:

答案 0 :(得分:0)

onCreateView()中,只需调整您在chartButton的{​​{1}}方法中编写的代码,具体为:

onClick()

然后返回view.addView(chart, new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); } });