用布局替换Fragmant




我想创建一个带有导航抽屉的应用程序。我使用了这个示例链接https://developer.android.com/training/implementing-navigation/nav-drawer.html
但现在我有一个问题。有可能更换Fragment with a Layout吗?

您的意思是,与其在抽屉中的项目单击时创建片段,不如在某个地方设置一些布局?我认为这里不方便,也不是最好的做法。你可以做的一件事是,你可以膨胀布局,并以片段的形式返回,这实际上等于设置布局。因此,您应该做的是,在fragment的onCreateView(..)方法中展开布局,并返回如下所示:

// onCreateView of fragment
@Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.YOUR_LAYOUT, container, false);
             // set values for view components if necessary.
            return rootView;
}

是,通过保存FrameLayout引用:

FrameLayout frame = findViewById(R.id.content_frame);

具有类似的类

private class DrawerItemClickListener implements ListView.OnItemClickListener {
    final FrameLayout frame;
    final Context context;
    public DrawerItemClickListener(FrameLayout f, Context c){
      this.frame = f;
      this.context = c;
    }
    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        View detail = getViewForOption(position);
        frame.removeAllViews();
        frame.addView(detail);
    }
    private View getViewForOption(int position){
      //--inflate and return different detail views--
      switch(position){
       case 1:
         return LayoutInflator.from(context).inflate(R.layout.detail_1,null,false);
       case 2:
         return LayoutInflator.from(context).inflate(R.layout.detail_2,null,false);
      }
    }
}

最新更新