ViewPager 使用一
package com.example.viewpager; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.support.v4.view.PagerTabStrip; import android.support.v4.view.ViewPager; import android.view.View; public class MainActivity extends Activity { private List<View> viewList; private ViewPager pager; private PagerTabStrip tab; private List<String> titleList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewList = new ArrayList<View>(); View view1 = View.inflate(this, R.layout.view1, null); View view2 = View.inflate(this, R.layout.view2, null); View view3 = View.inflate(this, R.layout.view3, null); View view4 = View.inflate(this, R.layout.view4, null); viewList.add(view1); viewList.add(view2); viewList.add(view3); viewList.add(view4); //为页卡设置标题 titleList = new ArrayList<String>(); titleList.add("第一页"); titleList.add("第二页"); titleList.add("第三页"); titleList.add("第四页"); tab = (PagerTabStrip) findViewById(R.id.pagerTitle); //为PageTabStrip设置一些属性 tab.setBackgroundColor(Color.YELLOW); tab.setTextColor(Color.RED); tab.setDrawFullUnderline(false); tab.setTabIndicatorColor(Color.GREEN); pager = (ViewPager) findViewById(R.id.pager); //创建PagerAdapter的适配器 MyPagerAdapter adapter = new MyPagerAdapter(viewList,titleList); //Viewpage加载适配器 pager.setAdapter(adapter); } }
xml文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" > <android.support.v4.view.PagerTabStrip android:id="@+id/pagerTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="top" > </android.support.v4.view.PagerTabStrip> </android.support.v4.view.ViewPager> </RelativeLayout>
view1.xml文件和view2,3,4文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical|center_horizontal" android:text="第一个界面" /> </LinearLayout>
一样的!