在DrawerItemClickListener(NavigationDrawer)中访问片段的视图 - 在onCreateView()之外

时间:2015-05-29 06:28:30

标签: android android-fragments navigation-drawer

我尝试在DrawerItemClickListener中获取Fragment的视图。但我无法访问正确的视图!

MapFragment:

public class MapFragment extends Fragment {
    public View rootView;

    public MapFragment() {
        // Empty constructor required for fragment subclasses
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.fragment_map, container, false);

        return rootView;
    }
}

DrawerItemClickListener:

private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Object myView = rootView.findViewById(R.id.mapview);
    }
}

如何在DrawerItemClickListener中访问我的'rootView'?

1 个答案:

答案 0 :(得分:0)

首先,您不必自己存储视图。你可以使用getView();
您也可以移动代码

Object myView = rootView.findViewById(R.id.mapview);

进入onCreateView,并将对象myView存储为类的字段。然后在DrawerItemClickListener

中随意执行任何操作