Android 在来自主活动的片段中创建的访问视图

Android 在来自主活动的片段中创建的访问视图,android,Android,我在一个片段中创建了一个视图 public static class GraphSectionFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { GraphView view = new GraphView(

我在一个片段中创建了一个视图

public static class GraphSectionFragment extends Fragment 
{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) 
    {
        GraphView view = new GraphView(getActivity());
        view.setGraphType(GraphView.GraphType.Oscillator);          
        return view;
    }
}
现在我需要从主活动访问GraphView对象。我该怎么办? 我试过这种方法,但不起作用

GraphSectionFragment fr = (GraphSectionFragment) m_SectionsPagerAdapter.getItem(0);
View v = fr.getView();
GraphView graph = (GraphView)v;
graph.setData(0, m_DeviceThread.getRangeDataI());

m_SectionsPagerAdapter是从FragmentPagerAdapter继承的类的对象。Fragment.getView返回某个奇怪类的视图,而不是GraphView。

您可以通过执行以下操作来检索活动:

(MyActivity)getActivity();
因此,如果在类中将
GraphView
设置为公共变量,则可以执行以下操作:

GraphView graph = ((MyActivity)getActivity()).myGraph;
或设置访问器函数:

GraphView graph = ((MyActivity)getActivity()).getGraphView();

你会得到你的答案。 根据您的实现,您可以通过任何一种方式访问活动中的片段

要在扩展FragmentActivity的类中获取片段实例,请执行以下操作:

MyclassFragment instanceFragment= (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

要在扩展片段的类中获取片段实例,请执行以下操作:

MyclassFragment instanceFragment =
(MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);