Android ViewPage的使用(一)
ViewPage是一个简单的页面切换组件,左右滑动的话,有效果,和ListView一样
也需要配合适配器(PagerAdapter)来使用。
先来个效果图吧
先随便创建3个view页面,用于放到 ViewPage里面
view_one.xml
view_two.xml 和上面页面内容一样,
view_there.xml 和上面页面内容一样,
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView" android:layout_width="140dp" android:layout_height="101dp" android:text="one" android:textSize="30sp" /> </android.support.constraint.ConstraintLayout>
主页面activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <android.support.v4.view.ViewPager android:id="@+id/vpager_one" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"> </android.support.v4.view.ViewPager> </android.support.constraint.ConstraintLayout>
适配器:
package action.sun.com.viewpage1; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; public class MyPagerAdapter extends PagerAdapter { private ArrayList<View> viewLists; public MyPagerAdapter() { } public MyPagerAdapter(ArrayList<View> viewLists) { super(); this.viewLists = viewLists; } @Override public int getCount() { return viewLists.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(viewLists.get(position)); return viewLists.get(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(viewLists.get(position)); } }
主页面调用代码:
package action.sun.com.viewpage1; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private ViewPager vpager; private ArrayList<View> aList; private MyPagerAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); vpager = (ViewPager) findViewById(R.id.vpager_one); aList = new ArrayList<View>(); LayoutInflater li = getLayoutInflater(); aList.add(li.inflate(R.layout.view_one,null,false)); aList.add(li.inflate(R.layout.view_two,null,false)); aList.add(li.inflate(R.layout.view_there,null,false)); mAdapter = new MyPagerAdapter(aList); vpager.setAdapter(mAdapter); } }
以上,基本的ViewPage就能够实现了。