2012-04-22 43 views
0

我想从图表和onCreateView的片段中的一些按钮返回布局。我不知道如何将这两种观点合为一体。我只能返回图表或布局没有图表:如何使用图表在Android中使用achartengine返回布局

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> 

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

回答

0

onCreateView()刚刚适应你chartButtononClick()方法写的代码,具体是:

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

,然后返回view

+0

上面的想法很好,但应该是'layout.add()'而不是'view.add()'。 – rgb 2012-04-23 19:43:49

+0

对不起,对不起;) – Venator85 2012-04-23 19:48:48

+0

非常感谢您的回答:) – rgb 2012-04-23 20:22:07