2014-08-30 45 views
0

我正在创建一个Android应用程序,我有几个自定义的ViewGroups我创建并希望添加一个ViewPager到我的MainActivity,以便我可以在屏幕之间来回切换视图。然而,它看起来像添加到ViewPager的项目必须是一个片段。我是否需要为每个自定义ViewGroup创建一个单独的片段,或者是否有直接添加它们的方式?使用ViewPager与自定义ViewGroups

+1

根本不需要片段,请参阅http://developer.android.com/reference/android/support/v4/view/PagerAdapter.html – pskink 2014-08-30 18:34:02

回答

0

不,你不需要它。

在您的FragmenAdapter中,根据当前位置为每个片段设置所需的ID布局。

// FragmentStatePagerAdapter

public class DynamicViewsFragmentAdapter extends FragmentStatePagerAdapter { 

public DynamicViewsFragmentAdapter(FragmentActivity activity) { 
    super(activity.getSupportFragmentManager()); 
} 

@Override 
public Fragment getItem(int position) { 
    DynamicViewsFragment fragment = new DynamicViewsFragment(); 
    int idLayout = getIdLayoutBasedOnPosition(position); 
    fragment.setIdLayout(idLayout); 
    return fragment; 
} 

@Override 
public int getCount() { 
    return 3; 
} 

private int getIdLayoutBasedOnPosition(int position) { 
    if(position == 0) return R.layout.one; 
    else if (position == 1) return R.layout.one; 
    else return R.layout.three; 
} 
} 

//片段

public class DynamicViewsFragment extends Fragment { 

private int _idLayout; 

public void setIdLayout(int idLayout) { 
    _idLayout = idLayout; 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    super.onCreateView(inflater, container, savedInstanceState); 
    View rootView = inflater.inflate(_idLayout, container, false); 
    return rootView; 
} 

}