从主要活动在Fragment中创建的Access View

时间:2012-08-10 16:11:21

标签: android

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

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;
    }
}

现在我需要从main活动访问我的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。

2 个答案:

答案 0 :(得分:3)

您将在this link得到答案。 您可以根据您的实现以任一方式访问活动中的片段。

在扩展FragmentActivity的类中获取片段实例:

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

OR

在扩展Fragment的类中获取片段实例:

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

答案 1 :(得分:-1)

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

(MyActivity)getActivity();

因此,如果您的GraphView设置为班级中的公共变量,则可以执行以下操作:

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

或设置访问者功能:

GraphView graph = ((MyActivity)getActivity()).getGraphView();
相关问题