Fragment+ViewPager

多数情况是Fragment与ViewPager配合使用,产生滑动切换效果。

知识点:

1 ViewPager的建立

2 ViewPager与Fragment绑定

3 Fragment动态加载数据

Fragment+ViewPager_第1张图片

1 ViewPager建立

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" />

2 )创建新的viewpager:

mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(appSelectPagerAdapter);


2 ViewPager与Fragment绑定

利用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;
		}

	}


2)viewPager与Fragment绑定:
/**
	 * 自定义的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;
		}

	}

3 Fragment动态加载数据

每次加载预置数据的时候是通过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;
		}

在自定义的Fragment的onCreateView中获得参数

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;
		}


本例代码:http://download.csdn.net/detail/xiaoleiacm/9482716


 

你可能感兴趣的:(android,viewpager,Fragment)