多数情况是Fragment与ViewPager配合使用,产生滑动切换效果。
1 ViewPager的建立
2 ViewPager与Fragment绑定
3 Fragment动态加载数据
1) 在布局文件中加入ViewPager布局文件:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" />
mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(appSelectPagerAdapter);
利用FragmentPagerAdapter将自定义的Fragment进行绑定
1) 建立Frament
/** * 自定义的Fragment * * @author admin * */ public class myFragment extends Fragment { private TextView mtvcontent; @Override @Nullable public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // TODO Auto-generated method stub、 View view = inflater.inflate(R.layout.fragment_select_dummy, null); mtvcontent = (TextView) view.findViewById(R.id.tvcontent); Bundle arguments = getArguments(); String str = (String) arguments.get("key"); mtvcontent.setText(str); return view; } }
/** * 自定义的Fragment * * @author admin * */ public class myFragment extends Fragment { private TextView mtvcontent; @Override @Nullable public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // TODO Auto-generated method stub、 View view = inflater.inflate(R.layout.fragment_select_dummy, null); mtvcontent = (TextView) view.findViewById(R.id.tvcontent); Bundle arguments = getArguments(); String str = (String) arguments.get("key"); mtvcontent.setText(str); return view; } }
每次加载预置数据的时候是通过SetArgments(),与GetArgments()来实现的。
在Adapter中getItem()进行设置参数
@Override public Fragment getItem(int arg0) { // TODO Auto-generated method stub /** * 不同的Fragment在通信的时候使用setArgments */ myFragment myFragment = new myFragment(); Bundle bundle = new Bundle(); bundle.putString("key", "Select " + arg0); myFragment.setArguments(bundle); return myFragment; }
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // TODO Auto-generated method stub、 View view = inflater.inflate(R.layout.fragment_select_dummy, null); mtvcontent = (TextView) view.findViewById(R.id.tvcontent); Bundle arguments = getArguments(); String str = (String) arguments.get("key"); mtvcontent.setText(str); return view; }