如何将数据从活动发送到片段以更新图形?

时间:2015-04-27 10:03:46

标签: android android-fragments android-activity android-graphview

public class GraphUpdate extends Fragment {
    private final Handler mHandler = new Handler();
    private Runnable mTimer;
    private LineGraphSeries<DataPoint> mSeries;
    private double graph2LastXValue = 5d;
    private int value;
    private String TAG = "FRAGMENT";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        GraphView graph = (GraphView) rootView.findViewById(R.id.graph);
        mSeries = new LineGraphSeries<DataPoint>();
        graph.addSeries(mSeries);
        graph.getViewport().setXAxisBoundsManual(true);
        graph.getViewport().setMinX(0);
        graph.getViewport().setMaxX(40);

        return rootView;
   }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
        mTimer = new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "onResume");
                graph2LastXValue += 1d;
                mSeries.appendData(new DataPoint(graph2LastXValue, value), true, 40);
                mHandler.postDelayed(this, 1000);
            }

        };
        mHandler.postDelayed(mTimer, 300);
     }

我必须使用Main_Activity的数据更新此图表。

运行时的MainActivity将一些数据发送到我的Fragment。 GraphUpdate用数据更新图表。

最好的方法是什么?我已经阅读了如何使用Interface或Bundle将数据从活动发送到片段,但是为了保持更新图表最佳解决方案是什么?

4 个答案:

答案 0 :(得分:2)

只需在片段中创建一个实际更新图形的方法,并使用您已在片段simple.e.x中声明的活动调用更新图形方法中的片段对象。

frag=(cast)getSupportFragmentManager().findFragmentByTag("fragment tag");
frag.updateGraph() from your activity. 
and declare updateGraph method in fragment.  

答案 1 :(得分:0)

例如,您可以在GraphUpdate类中创建一个名为updateFragment()的方法。然后,从您的活动中调用该方法。

答案 2 :(得分:0)

您不需要使用接口也只需在该片段中编写一个公共方法。只需调用该方法。如果要发送数据,请使用方法参数。

答案 3 :(得分:0)

在您的片段中使用您选择的延迟时间的处理程序,并在您的活动中调用所需的方法,获取数据并更新您的图表,以便在可运行的内部继续更新使用后延迟