上一节提到了用ViewPager做ImageView的切换,但这个毕竟局限。在Activity中,只有一种组件是必需的,那就是Fragment。这一节我尝试一下在ViewPager中放Fragment。
我先建了三个Fragment
XML:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/fg1_txId" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" /> <Button android:id="@+id/fg1_btId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="test1"/> </LinearLayout>
Fragment1:
public class Fragment1 extends android.support.v4.app.Fragment { Button bt; TextView tv; static int i=0; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View fragment1Layout = inflater.inflate(R.layout.fragment1_layout,container,false); return fragment1Layout; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); bt = (Button) getActivity().findViewById(R.id.fg1_btId); tv = (TextView) getActivity().findViewById(R.id.fg1_txId); tv.setText(""+i); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { i++; tv.setText(""+i); } }); } }
Fragment2和Fragment3与上面的相似。
然后是主界面的XML:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v4.view.ViewPager android:id="@+id/viewPagerId" android:layout_width="match_parent" android:layout_height="match_parent"> </android.support.v4.view.ViewPager> </LinearLayout>
这跟上一节没什么两样。
接下来是主界面的Activity
先声明类:
public class MainActivity extends FragmentActivity { List<android.support.v4.app.Fragment> mFragment = new ArrayList<android.support.v4.app.Fragment>(); FragmentManager fragmentManager; ViewPager viewPager; Fragment1 fragment1; Fragment2 fragment2; Fragment3 fragment3;
然后获取实例,设置动画
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewPager = (ViewPager) findViewById(R.id.viewPagerId); fragment1 = new Fragment1(); fragment2 = new Fragment2(); fragment3 = new Fragment3(); mFragment.add(fragment1); mFragment.add(fragment2); mFragment.add(fragment3); //设置ViewPager翻页动画 viewPager.setPageTransformer(true , new DepthPageTransformer());
最后,设置ViewPager的适配器
viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) { @Override public android.support.v4.app.Fragment getItem(int i) { return mFragment.get(i); } @Override public int getCount() { return mFragment.size(); } });
以上。