根据我对此thread的理解,片段可以很容易地被其他片段取代。
然而在我的情况下,我有2个片段组合在可滚动的Activity中,所以当我说“移动”时,我的意思是从片段向左或向右或从左到左,而不用另一个片段替换任何片段。这有可能吗?
答案 0 :(得分:1)
你可以使用ViewPager。在您的适配器类上,您将不得不通过getItem()在片段之间切换。 Eclipse / new AndroidProject / swipe with / out标签。并查看Android生成的示例代码。
编辑:
创建xml文件,将其称为main_activity.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main" >
<android.support.v4.view.PagerTitleStrip
android:id="@+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#FAFAFA"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#36466E" />
创建一个类称为Main
public class Main extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
Context ctx;
static MySQLiteHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mSectionsPagerAdapter.notifyDataSetChanged();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch(position){
case 0:
fragment = new GridApp();
break;
case 1:
fragment = new ListApp();
break;
}
return fragment;
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Select App";
case 1:
return "Selected Apps";
}
return null;
}
}
}
现在创建一个名为GridApp
和ListApp
GridApp类。
public class GridApp extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridpp,
container, false);
}
}
ListApp类
public class GridApp extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.listapp,
container, false);
}
}
你完成了。