0

我正在尝试从片段中的 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>

工作正常,但我不知道如何在片段中做到这一点。

4

1 回答 1

0

只需调整您在's方法onCreateView()中编写的代码,特别是:chartButtononClick()

view.addView(chart, new LayoutParams(
        LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        }
    });

然后返回view

于 2012-04-22T10:58:47.930 回答