Android基于ViewPager Fragment实现选项卡
程序员文章站
2023-12-10 13:43:10
先给大家展示效果图:
1.新建testfragmen继承fragment
public class testfragment extends fragm...
先给大家展示效果图:
1.新建testfragmen继承fragment
public class testfragment extends fragment { private static final string tag = "testfragment"; private string hello;// = "hello android"; private string defaulthello = "default value"; private map<string, object=""> maplist; static testfragment newinstance(string s, map<string, object=""> map) { testfragment newfragment = new testfragment(); // bundle bundle = new bundle(); // bundle.putstring("hello", s); // newfragment.setarguments(bundle); final serializablemap mymap=new serializablemap(); mymap.setmap(map); bundle bundle = new bundle(); bundle.putserializable("map", mymap); newfragment.setarguments(bundle); return newfragment; } @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); log.d(tag, "testfragment-----oncreate"); bundle args = getarguments(); // hello = args != null ? args.getstring("hello") : defaulthello; bundle bundle = getarguments(); serializablemap serializablemap = (serializablemap) bundle.get("map"); maplist =serializablemap.getmap(); } @override public view oncreateview(layoutinflater inflater, viewgroup container,bundle savedinstancestate) { log.d(tag, "testfragment-----oncreateview"); view view = inflater.inflate(r.layout.lay1, container, false); // textview viewhello = (textview) view.findviewbyid(r.id.tv_hello); //viewhello.settext(maplist.get("userid")+"time"); listview lv = (listview) view.findviewbyid(r.id.listview3); contactadapter hc = new contactadapter(getactivity().getapplicationcontext(),getcontact()); lv.setadapter(hc); lv.setcachecolorhint(0); return view; } private arraylist<contact> getcontact(){ arraylist<contact> hclist = new arraylist<contact>(); for(int i=0;i<10;i++) { contact c0 = new contact(); c0.settxpath(r.drawable.more_game+""); c0.setname(maplist.get("userid")+" 年龄:"+maplist.get("age")); hclist.add(c0); } return hclist; } @override public void ondestroy() { super.ondestroy(); log.d(tag, "testfragment-----ondestroy"); } } </contact></contact></contact></string,></string,>
2.myfragmentpageradapter继承fragmentpageradapter
public class myfragmentpageradapter extends fragmentpageradapter { private arraylist<fragment> fragmentslist; public myfragmentpageradapter(fragmentmanager fm) { super(fm); } public myfragmentpageradapter(fragmentmanager fm, arraylist<fragment> fragments) { super(fm); this.fragmentslist = fragments; } @override public int getcount() { return fragmentslist.size(); } @override public fragment getitem(int arg0) { return fragmentslist.get(arg0); } @override public int getitemposition(object object) { return super.getitemposition(object); } } </fragment></fragment>
3.mainactivity 要继承fragmentactivity
public class mainactivity extends fragmentactivity { private static final string tag = "mainactivity"; private viewpager mpager; private arraylist<fragment> fragmentslist; private imageview ivbottomline; private textview tvtabactivity, tvtabgroups, tvtabfriends, tvtabchat; private int currindex = 0; private int bottomlinewidth; private int offset = 0; private int position_one; private int position_two; private int position_three; private resources resources; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); requestwindowfeature(window.feature_no_title); setcontentview(r.layout.main); resources = getresources(); initwidth(); inittextview(); initviewpager(); } private void inittextview() { tvtabactivity = (textview) findviewbyid(r.id.tv_tab_activity); tvtabgroups = (textview) findviewbyid(r.id.tv_tab_groups); tvtabfriends = (textview) findviewbyid(r.id.tv_tab_friends); tvtabchat = (textview) findviewbyid(r.id.tv_tab_chat); tvtabactivity.setonclicklistener(new myonclicklistener(0)); tvtabgroups.setonclicklistener(new myonclicklistener(1)); tvtabfriends.setonclicklistener(new myonclicklistener(2)); tvtabchat.setonclicklistener(new myonclicklistener(3)); } private void initviewpager() { mpager = (viewpager) findviewbyid(r.id.vpager); fragmentslist = new arraylist<fragment>(); map<string, object=""> parammap = new hashmap<string, object="">(); parammap.put("userid","小洪"); parammap.put("age",23); map<string, object=""> parammap2 = new hashmap<string, object="">(); parammap2.put("userid","vatty"); parammap2.put("age",24); map<string, object=""> parammap3 = new hashmap<string, object="">(); parammap3.put("userid","小明"); parammap3.put("age",25); map<string, object=""> parammap4 = new hashmap<string, object="">(); parammap4.put("userid","hongshengpeng.com"); parammap4.put("age",26); fragment activityfragment = testfragment.newinstance("hello activity.",parammap); fragment groupfragment = testfragment.newinstance("hello group.",parammap2); fragment friendsfragment=testfragment.newinstance("hello friends.",parammap3); fragment chatfragment=testfragment.newinstance("hello chat.",parammap4); fragmentslist.add(activityfragment); fragmentslist.add(groupfragment); fragmentslist.add(friendsfragment); fragmentslist.add(chatfragment); mpager.setadapter(new myfragmentpageradapter(getsupportfragmentmanager(), fragmentslist)); mpager.setcurrentitem(0); mpager.setonpagechangelistener(new myonpagechangelistener()); } private void initwidth() { ivbottomline = (imageview) findviewbyid(r.id.iv_bottom_line); bottomlinewidth = ivbottomline.getlayoutparams().width; log.d(tag, "cursor imageview width=" + bottomlinewidth); displaymetrics dm = new displaymetrics(); getwindowmanager().getdefaultdisplay().getmetrics(dm); int screenw = dm.widthpixels; offset = (int) ((screenw / 4.0 - bottomlinewidth) / 2); log.i("mainactivity", "offset=" + offset); position_one = (int) (screenw / 4.0); position_two = position_one * 2; position_three = position_one * 3; } public class myonclicklistener implements view.onclicklistener { private int index = 0; public myonclicklistener(int i) { index = i; } @override public void onclick(view v) { mpager.setcurrentitem(index); } }; public class myonpagechangelistener implements onpagechangelistener { @override public void onpageselected(int arg0) { animation animation = null; switch (arg0) { case 0: if (currindex == 1) { animation = new translateanimation(position_one, 0, 0, 0); tvtabgroups.settextcolor(resources.getcolor(r.color.lightwhite)); } else if (currindex == 2) { animation = new translateanimation(position_two, 0, 0, 0); tvtabfriends.settextcolor(resources.getcolor(r.color.lightwhite)); } else if (currindex == 3) { animation = new translateanimation(position_three, 0, 0, 0); tvtabchat.settextcolor(resources.getcolor(r.color.lightwhite)); } tvtabactivity.settextcolor(resources.getcolor(r.color.white)); break; case 1: if (currindex == 0) { animation = new translateanimation(0, position_one, 0, 0); tvtabactivity.settextcolor(resources.getcolor(r.color.lightwhite)); } else if (currindex == 2) { animation = new translateanimation(position_two, position_one, 0, 0); tvtabfriends.settextcolor(resources.getcolor(r.color.lightwhite)); } else if (currindex == 3) { animation = new translateanimation(position_three, position_one, 0, 0); tvtabchat.settextcolor(resources.getcolor(r.color.lightwhite)); } tvtabgroups.settextcolor(resources.getcolor(r.color.white)); break; case 2: if (currindex == 0) { animation = new translateanimation(0, position_two, 0, 0); tvtabactivity.settextcolor(resources.getcolor(r.color.lightwhite)); } else if (currindex == 1) { animation = new translateanimation(position_one, position_two, 0, 0); tvtabgroups.settextcolor(resources.getcolor(r.color.lightwhite)); } else if (currindex == 3) { animation = new translateanimation(position_three, position_two, 0, 0); tvtabchat.settextcolor(resources.getcolor(r.color.lightwhite)); } tvtabfriends.settextcolor(resources.getcolor(r.color.white)); break; case 3: if (currindex == 0) { animation = new translateanimation(0, position_three, 0, 0); tvtabactivity.settextcolor(resources.getcolor(r.color.lightwhite)); } else if (currindex == 1) { animation = new translateanimation(position_one, position_three, 0, 0); tvtabgroups.settextcolor(resources.getcolor(r.color.lightwhite)); } else if (currindex == 2) { animation = new translateanimation(position_two, position_three, 0, 0); tvtabfriends.settextcolor(resources.getcolor(r.color.lightwhite)); } tvtabchat.settextcolor(resources.getcolor(r.color.white)); break; } currindex = arg0; animation.setfillafter(true); animation.setduration(300); ivbottomline.startanimation(animation); } @override public void onpagescrolled(int arg0, float arg1, int arg2) { } @override public void onpagescrollstatechanged(int arg0) { } } }</string,></string,></string,></string,></string,></string,></string,></string,></fragment></fragment>
4.分别新建lay1.xml、 lay2.xml 、lay3.xml
lay1.xml
<!--?xml version="1.0" encoding="utf-8"?--> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#fff" android:orientation="vertical"> <textview android:id="@+id/tv_hello" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="textview" android:visibility="gone"> <listview android:id="@+id/listview3" android:layout_width="match_parent" android:layout_height="wrap_content" android:cachecolorhint="@android:color/transparent" android:divider="@drawable/reader_item_divider" android:listselector="@android:color/transparent"> </listview> </textview></linearlayout>
lay2.xml
<!--?xml version="1.0" encoding="utf-8"?--> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="#ff8684"> </linearlayout>
lay3.xml与lay2.xml类型
<!--?xml version="1.0" encoding="utf-8"?--> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="#1586ff"> </linearlayout>
main.xml
<!--?xml version="1.0" encoding="utf-8"?--> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:umadsdk="http://schemas.android.com/apk/res/com.lovebus" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <linearlayout android:layout_width="match_parent" android:layout_height="48dip" android:background="@drawable/android_title_bg"> <imageview android:id="@+id/imageview1" android:layout_width="36dip" android:layout_height="36dip" android:layout_gravity="center_vertical" android:layout_marginleft="10dip" android:src="@drawable/more_game"> <textview android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginleft="10dip" android:text="乐够go" android:textappearance="?android:attr/textappearancelarge"> <imageview android:id="@+id/imageview2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:paddingleft="10dip" android:src="@drawable/status_online" android:visibility="gone"> </imageview></textview></imageview></linearlayout> <linearlayout android:id="@+id/linearlayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingbottom="5dip" android:paddingtop="10dip" android:background="@color/coral"> <textview android:id="@+id/tv_tab_activity" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text="@string/tab_1" android:textcolor="@color/white" android:textsize="18sp"> <textview android:id="@+id/tv_tab_groups" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text="@string/tab_2" android:textcolor="@color/lightwhite" android:textsize="18sp"> <textview android:id="@+id/tv_tab_friends" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text="@string/tab_3" android:textcolor="@color/lightwhite" android:textsize="18sp"> <textview android:id="@+id/tv_tab_chat" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1.0" android:gravity="center" android:text="@string/tab_4" android:textcolor="@color/lightwhite" android:textsize="18sp"> </textview></textview></textview></textview></linearlayout> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" android:orientation="vertical" android:paddingbottom="3dip"> <imageview android:id="@+id/iv_bottom_line" android:layout_width="40dip" android:layout_height="2dip" android:layout_marginleft="20dip" android:scaletype="matrix" android:src="#fff"> </imageview></linearlayout> </linearlayout> </android.support.v4.view.viewpager></linearlayout>
ps:viewpager + fragment实现滑动标签页
viewpager 结合fragment实现一个activity里包含多个可滑动的标签页,每个标签页可以有独立的布局及响应。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <linearlayout 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:orientation="vertical"> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <textview android:id="@+id/tv_guid1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:gravity="center" android:text="特性1" android:textsize="18sp"/> <textview android:id="@+id/tv_guid2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:gravity="center" android:text="特性2" android:textsize="18sp"/> <textview android:id="@+id/tv_guid3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:gravity="center" android:text="特性3 " android:textsize="18sp"/> <textview android:id="@+id/tv_guid4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:gravity="center" android:text="特性4" android:textsize="18sp"/> </linearlayout> <imageview android:id="@+id/cursor" android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaletype="matrix" android:src="@drawable/cursor"/> <android.support.v4.view.viewpager android:id="@+id/viewpager" android:layout_width="fill_parent" android:layout_height="fill_parent" android:flipinterval="30" android:persistentdrawingcache="animation"/> </linearlayout>
mainactivity.java
package com.example.viewpagernfragment; import java.util.arraylist; import android.graphics.bitmapfactory; import android.graphics.matrix; import android.os.bundle; import android.support.v4.app.fragment; import android.support.v4.app.fragmentactivity; import android.support.v4.view.viewpager; import android.support.v4.view.viewpager.onpagechangelistener; import android.util.displaymetrics; import android.view.menu; import android.view.view; import android.view.animation.animation; import android.view.animation.translateanimation; import android.widget.imageview; import android.widget.textview; import android.widget.toast; public class mainactivity extends fragmentactivity { private viewpager mpager; private arraylist<fragment> fragmentlist; private imageview image; private textview view1, view2, view3, view4; private int currindex;//当前页卡编号 private int bmpw;//横线图片宽度 private int offset;//图片移动的偏移量 @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); inittextview(); initimage(); initviewpager(); } /* * 初始化标签名 */ public void inittextview(){ view1 = (textview)findviewbyid(r.id.tv_guid1); view2 = (textview)findviewbyid(r.id.tv_guid2); view3 = (textview)findviewbyid(r.id.tv_guid3); view4 = (textview)findviewbyid(r.id.tv_guid4); view1.setonclicklistener(new txlistener(0)); view2.setonclicklistener(new txlistener(1)); view3.setonclicklistener(new txlistener(2)); view4.setonclicklistener(new txlistener(3)); } public class txlistener implements view.onclicklistener{ private int index=0; public txlistener(int i) { index =i; } @override public void onclick(view v) { // todo auto-generated method stub mpager.setcurrentitem(index); } } /* * 初始化图片的位移像素 */ public void initimage(){ image = (imageview)findviewbyid(r.id.cursor); bmpw = bitmapfactory.decoderesource(getresources(), r.drawable.cursor).getwidth(); displaymetrics dm = new displaymetrics(); getwindowmanager().getdefaultdisplay().getmetrics(dm); int screenw = dm.widthpixels; offset = (screenw/4 - bmpw)/2; //imgageview设置平移,使下划线平移到初始位置(平移一个offset) matrix matrix = new matrix(); matrix.posttranslate(offset, 0); image.setimagematrix(matrix); } /* * 初始化viewpager */ public void initviewpager(){ mpager = (viewpager)findviewbyid(r.id.viewpager); fragmentlist = new arraylist<fragment>(); fragment btfragment= new buttonfragment(); fragment secondfragment = testfragment.newinstance("this is second fragment"); fragment thirdfragment = testfragment.newinstance("this is third fragment"); fragment fourthfragment = testfragment.newinstance("this is fourth fragment"); fragmentlist.add(btfragment); fragmentlist.add(secondfragment); fragmentlist.add(thirdfragment); fragmentlist.add(fourthfragment); //给viewpager设置适配器 mpager.setadapter(new myfragmentpageradapter(getsupportfragmentmanager(), fragmentlist)); mpager.setcurrentitem(0);//设置当前显示标签页为第一页 mpager.setonpagechangelistener(new myonpagechangelistener());//页面变化时的监听器 } public class myonpagechangelistener implements onpagechangelistener{ private int one = offset *2 +bmpw;//两个相邻页面的偏移量 @override public void onpagescrolled(int arg0, float arg1, int arg2) { // todo auto-generated method stub } @override public void onpagescrollstatechanged(int arg0) { // todo auto-generated method stub } @override public void onpageselected(int arg0) { // todo auto-generated method stub animation animation = new translateanimation(currindex*one,arg0*one,0,0);//平移动画 currindex = arg0; animation.setfillafter(true);//动画终止时停留在最后一帧,不然会回到没有执行前的状态 animation.setduration(200);//动画持续时间0.2秒 image.startanimation(animation);//是用imageview来显示动画的 int i = currindex + 1; toast.maketext(mainactivity.this, "您选择了第"+i+"个页卡", toast.length_short).show(); } } @override public boolean oncreateoptionsmenu(menu menu) { // inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; } }
谷歌官方认为,viewpager应该和fragment一起使用时,此时viewpager的适配器是fragmentpageradapter,当你实现一个fragmentpageradapter,你必须至少覆盖以下方法:
getcount()
getitem()
如果viewpager没有和fragment一起,viewpager的适配器是pageradapter,它是基类提供适配器来填充页面viewpager内部,当你实现一个pageradapter,你必须至少覆盖以下方法:
instantiateitem(viewgroup, int) destroyitem(viewgroup, int, object) getcount() isviewfromobject(view, object) [java] view plaincopy package com.example.viewpagernfragment; import java.util.arraylist; import android.support.v4.app.fragment; import android.support.v4.app.fragmentmanager; import android.support.v4.app.fragmentpageradapter; public class myfragmentpageradapter extends fragmentpageradapter{ arraylist<fragment> list; public myfragmentpageradapter(fragmentmanager fm,arraylist<fragment> list) { super(fm); this.list = list; } @override public int getcount() { return list.size(); } @override public fragment getitem(int arg0) { return list.get(arg0); } } [java] view plaincopy package com.example.viewpagernfragment; import android.os.bundle; import android.support.v4.app.fragment; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.button; import android.widget.toast; public class buttonfragment extends fragment{ button mybutton; @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.guide_1, container, false);//关联布局文件 mybutton = (button)rootview.findviewbyid(r.id.mybutton);//根据rootview找到button //设置按键监听事件 mybutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub toast.maketext(buttonfragment.this.getactivity(), "button is click!", toast.length_short).show(); } }); return rootview; } } [java] view plaincopy package com.example.viewpagernfragment; import android.os.bundle; import android.support.v4.app.fragment; import android.util.log; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.textview; public class testfragment extends fragment { private static final string tag = "testfragment"; private string hello;// = "hello android"; private string defaulthello = "default value"; static testfragment newinstance(string s) { testfragment newfragment = new testfragment(); bundle bundle = new bundle(); bundle.putstring("hello", s); newfragment.setarguments(bundle); //bundle还可以在每个标签里传送数据 return newfragment; } @override public view oncreateview(layoutinflater inflater, viewgroup container,bundle savedinstancestate) { log.d(tag, "testfragment-----oncreateview"); bundle args = getarguments(); hello = args != null ? args.getstring("hello") : defaulthello; view view = inflater.inflate(r.layout.guide_2, container, false); textview viewhello = (textview) view.findviewbyid(r.id.tv); viewhello.settext(hello); return view; } } <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff0000ff" > <button android:id="@+id/mybutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hit me" android:gravity="center"/> </relativelayout> [html] view plaincopy <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="#158684" > <textview android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="textview" /> </relativelayout>
推荐阅读
-
Android基于ViewPager Fragment实现选项卡
-
Android基于AlarmManager实现用户在线心跳功能示例
-
基于Android中手势交互的实现方法
-
基于Android中实现定时器的3种解决方法
-
Android编程实现ListView头部ViewPager广告轮询图效果
-
Android使用TabLayout+Fragment实现顶部选项卡
-
Android Fragment滑动组件ViewPager的实例详解
-
Android编程实现基于局域网udp广播自动建立socket连接的方法
-
Android中TabLayout+ViewPager实现tab和页面联动效果
-
Android使用TabLayou+fragment+viewpager实现滑动切换页面效果