Android中Viewpage+Fragment的简单实现

来源:互联网 发布:淘宝高颜值零食店铺 编辑:程序博客网 时间:2024/05/17 01:18

今天来说一下android中的Fragement配合ViewPage的使用方法。实现类似QQ页面的联系人,群组,动态之间的滑动效果。
界面效果

首先说一下,这个用法的原理是很简单的,需要一个MainActivity,在MainActivity中的Layout布局中加个ViewPager控件,另外如果想加个导航栏的话,就使用< include layout=”@layout/activity_main_top_tab” />加入导航栏布局。

activity_main.xml中的代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <include layout="@layout/activity_main_top_tab" />    <android.support.v4.view.ViewPager        android:id="@+id/id_page_vp"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1" >    </android.support.v4.view.ViewPager></LinearLayout>

包含导航栏的布局activity_main_top_tab.xml代码如下:

<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="wrap_content"android:orientation="vertical" ><LinearLayout    android:id="@+id/id_switch_tab_ll"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:orientation="horizontal"     android:baselineAligned="false"    >    <LinearLayout        android:id="@+id/id_tab_chat_ll"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_weight="1"        android:gravity="center"        android:orientation="horizontal"        android:padding="10dip" >        <TextView            android:id="@+id/id_chat_tv"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:gravity="center"            android:text="聊天"            android:textColor="#0000FF"            android:textSize="15dip" />    </LinearLayout>    <LinearLayout        android:id="@+id/id_tab_friend_ll"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_weight="1"        android:clickable="true"        android:gravity="center"        android:orientation="horizontal"        android:padding="10dip"        android:saveEnabled="false" >        <TextView            android:id="@+id/id_friend_tv"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:gravity="center"            android:text="好友"            android:textColor="#000000"            android:textSize="15dip" />    </LinearLayout>    <LinearLayout        android:id="@+id/id_tab_contacts_ll"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_weight="1"        android:focusable="false"        android:gravity="center"        android:orientation="horizontal"        android:padding="10dip" >        <TextView            android:id="@+id/id_contacts_tv"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:gravity="center"            android:text="通讯录"            android:textColor="#000000"            android:textSize="15dip" />    </LinearLayout></LinearLayout><ImageView    android:id="@+id/id_tab_line_iv"    android:layout_width="200dp"    android:layout_height="wrap_content"    android:contentDescription="tab"    android:background="@drawable/tab_selected_pressed_holo" ></ImageView><View    android:layout_width="match_parent"    android:layout_height="1dp"    android:background="#000000" /></LinearLayout>

我们的主界面已经写好了,接下来需要在里面添加Fragment了。
首先我们需要一个FragmentAdapter.java

package wxt.example.com.viewpagefragment;import java.util.ArrayList;import java.util.List;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter;public class FragmentAdapter extends FragmentPagerAdapter {/** * 存放fragment的List */List<Fragment> fragmentList = new ArrayList<Fragment>();/** * @param fm * @param fragmentList */public FragmentAdapter(FragmentManager fm,List<Fragment> fragmentList) {    super(fm);    this.fragmentList = fragmentList;}@Overridepublic Fragment getItem(int position) {    return fragmentList.get(position);}@Overridepublic int getCount() {    return fragmentList.size();}}

接下来我们新建三个Fragment,由于三个Fragment非常相似,这里只贴出一个的代码
ChatFragment.java的代码如下所示:

package wxt.example.com.viewpagefragment;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class ChatFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){    super.onCreateView(inflater, container, savedInstanceState);    View chatView = inflater.inflate(R.layout.activity_tab_chat,container,false);    return chatView;    }@Overridepublic void onActivityCreated(Bundle savedInstanceState){    super.onActivityCreated(savedInstanceState);}}

ChatFragment中onCreateView用到的布局信息是你在这一页需要显示在屏幕上的内容,使用自己写好的布局文件。
三个Fragment建好之后,接下来就需要在MainActivity中加入Fragment了。
MainActivity中的代码如下:

package wxt.example.com.viewpagefragment;import java.util.ArrayList;import java.util.List;import android.graphics.Color;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.util.Log;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;public class MainActivity extends FragmentActivity {private ViewPager mPageVp;private List<Fragment> mFragmentList = new ArrayList<Fragment>();private FragmentAdapter mFragmentAdapter;/** * Tab显示内容TextView */private TextView mTabChatTv, mTabContactsTv, mTabFriendTv;/** * Tab的那个引导线 */private ImageView mTabLineIv;/** * Fragment */private ChatFragment mChatFg;private FriendFragment mFriendFg;private ContactsFragment mContactsFg;/** * ViewPager的当前选中页 */private int currentIndex;/** * 屏幕的宽度 */private int screenWidth;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    findById();    init();    initTabLineWidth();}private void findById() {    mTabContactsTv = (TextView) this.findViewById(R.id.id_contacts_tv);    mTabChatTv = (TextView) this.findViewById(R.id.id_chat_tv);    mTabFriendTv = (TextView) this.findViewById(R.id.id_friend_tv);    mTabLineIv = (ImageView) this.findViewById(R.id.id_tab_line_iv);    mPageVp = (ViewPager) this.findViewById(R.id.id_page_vp);}private void init() {    mFriendFg = new FriendFragment();    mContactsFg = new ContactsFragment();    mChatFg = new ChatFragment();    mFragmentList.add(mChatFg);    mFragmentList.add(mFriendFg);    mFragmentList.add(mContactsFg);    mFragmentAdapter = new FragmentAdapter(            this.getSupportFragmentManager(), mFragmentList);    mPageVp.setAdapter(mFragmentAdapter);    mPageVp.setCurrentItem(0);    mPageVp.setOnPageChangeListener(new OnPageChangeListener() {        /**         * state滑动中的状态 有三种状态(0,1,2) 1:正在滑动 2:滑动完毕 0:什么都没做。         */        @Override        public void onPageScrollStateChanged(int state) {        }        /**         * position :当前页面,及你点击滑动的页面 offset:当前页面偏移的百分比         * offsetPixels:当前页面偏移的像素位置         */        @Override        public void onPageScrolled(int position, float offset,                int offsetPixels) {            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTabLineIv                    .getLayoutParams();            Log.e("offset:", offset + "");            /**             * 利用currentIndex(当前所在页面)和position(下一个页面)以及offset来             * 设置mTabLineIv的左边距 滑动场景:             * 记3个页面,             * 从左到右分别为0,1,2              * 0->1; 1->2; 2->1; 1->0             */            if (currentIndex == 0 && position == 0)// 0->1            {                lp.leftMargin = (int) (offset * (screenWidth * 1.0 / 3) + currentIndex                        * (screenWidth / 3));            } else if (currentIndex == 1 && position == 0) // 1->0            {                lp.leftMargin = (int) (-(1 - offset)                        * (screenWidth * 1.0 / 3) + currentIndex                        * (screenWidth / 3));            } else if (currentIndex == 1 && position == 1) // 1->2            {                lp.leftMargin = (int) (offset * (screenWidth * 1.0 / 3) +                 currentIndex*(screenWidth / 3));            } else if (currentIndex == 2 && position == 1) // 2->1            {                lp.leftMargin = (int) (-(1 - offset)                        * (screenWidth * 1.0 / 3) + currentIndex                        * (screenWidth / 3));            }            mTabLineIv.setLayoutParams(lp);        }        @Override        public void onPageSelected(int position) {            resetTextView();            switch (position) {            case 0:                mTabChatTv.setTextColor(Color.BLUE);                break;            case 1:                mTabFriendTv.setTextColor(Color.BLUE);                break;            case 2:                mTabContactsTv.setTextColor(Color.BLUE);                break;            }            currentIndex = position;        }    });}/** * 设置滑动条的宽度为屏幕的1/3(根据Tab的个数而定) */private void initTabLineWidth() {    //获得手机的常用信息    DisplayMetrics dpMetrics = new DisplayMetrics();    getWindow().getWindowManager().getDefaultDisplay()            .getMetrics(dpMetrics);    screenWidth = dpMetrics.widthPixels;    LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTabLineIv            .getLayoutParams();    lp.width = screenWidth / 3;    mTabLineIv.setLayoutParams(lp);}/** * 重置颜色 */private void resetTextView() {    mTabChatTv.setTextColor(Color.BLACK);    mTabFriendTv.setTextColor(Color.BLACK);    mTabContactsTv.setTextColor(Color.BLACK);}}

好了,现在全部工作都已经完成了,那么可以运行一下项目了,可以看到最开始那张图的想过了。当然可能做的并不美观,我们只实现了这个效果。想要什么样的界面效果,可以自行修改代码。

0 0
原创粉丝点击