关闭

实现滚动tab切换fragment + viewpager

标签: androidviewpagerfragment 滚动tab
296人阅读 评论(0) 收藏 举报
分类:


1.首先是界面的布局

<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"
    tools:context=".MainActivity" 
    android:orientation="vertical">
    
    
     <com.example.horizontalscrolltitle.layout.HorizontalTabList 
         android:id="@+id/title"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:scrollbars="@null"
         android:background="@color/color_gray"
         android:paddingTop="5dp"
         android:paddingBottom="5dp">
    
   <LinearLayout
       android:id="@+id/horizontal_tab"
       android:layout_width="wrap_content"
       android:layout_height="match_parent"
       android:orientation="horizontal"
       />
       
    </com.example.horizontalscrolltitle.layout.HorizontalTabList>


   <android.support.v4.view.ViewPager 
       android:id="@+id/viewPager"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:background="@color/color_text_selected"/>
   
</LinearLayout>



com.example.horizontalscrolltitle.layout.HorizontalTabList  继承自HorizontalScrollView来实现添加tab和横向滚动


2.HorizontalTabList类的实现


package com.example.horizontalscrolltitle.layout;


import java.util.ArrayList;
import java.util.List;


import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.example.horizontalscrolltitle.R;
import com.example.horizontalscrolltitle.utils.DisplayUtils;
import com.example.horizontalscrolltitle.utils.LayoutInflateUtils;


public class HorizontalTabList extends HorizontalScrollView{


private LinearLayout mLinearLayout;  //线性布局,用来添加tab
private List<String> mTabNameList;  / /tab名称列表
private OnItemSelectedListener mItemSelectedListener;//tab选中监听
private List<Integer> mWidthList;//记录每个tab的宽度,便于实现滚动效果
private View mSelectedView;//当前选中的tab
private List<View> mTabList;//所有tab

public HorizontalTabList(Context context, AttributeSet attrs) {
super(context, attrs);
}


@Override
protected void onFinishInflate() {//加载布局的时候执行
super.onFinishInflate();
mWidthList = new ArrayList<Integer>();
mTabList   = new ArrayList<View>();
mLinearLayout         = (LinearLayout) findViewById(R.id.horizontal_tab);
}

public void setTabList(OnItemSelectedListener onItemSelectedListener, List<String> tabs){
mItemSelectedListener = onItemSelectedListener;
mTabNameList = tabs;
mLinearLayout.removeAllViews();
for(int i = 0; i <  mTabNameList.size(); i ++){//添加tab 
final LinearLayout linearLayout = (LinearLayout) LayoutInflateUtils.inflate((Activity)getContext(), R.layout.tab_layout);//tab的布局
final TextView textView = (TextView) linearLayout.findViewById(R.id.tab);
linearLayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {//获得tab的宽度

@Override
public void onGlobalLayout() {
int width = linearLayout.getMeasuredWidth();
width = width + 2 * DisplayUtils.dp2px(getContext(), 1);
int position = Integer.parseInt(textView.getTag().toString());
if(position > 0){
mWidthList.add(position,mWidthList.get(position - 1) + width);
}else{
mWidthList.add(position, width);
}

}
});
textView.setTag(i);
textView.setText(mTabNameList.get(i));
mWidthList.add(0);
textView.setOnClickListener(new OnClickListener() {//点击tab实现滚动

@Override
public void onClick(View v) {
selectTab(v);

if(mItemSelectedListener != null){
int position = Integer.parseInt(v.getTag().toString());
if(position > 1){
scrollTo(mWidthList.get(position - 2), 0);
}
mItemSelectedListener.onItemSelected(Integer.parseInt(v.getTag().toString()));
}
}
});
mLinearLayout.addView(linearLayout);
mTabList.add(linearLayout);
}
}

public interface OnItemSelectedListener{
public void onItemSelected(int position);
}

public void setCurrentPosition(int position){//viewpager滑动的时候调用改方法来滚动tab
if(position < 2){
scrollTo(0, 0);
}else{
scrollTo(mWidthList.get(position - 2), 0);
}
selectTab(mTabList.get(position));
}

private void selectTab(View view){//选中tab
if(mSelectedView != null){
mSelectedView.setSelected(false);
}
view.setSelected(true);
mSelectedView = view;
}
}

3.在Activity中的使用

package com.example.horizontalscrolltitle;


import java.util.ArrayList;
import java.util.List;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Window;


import com.example.horizontalscrolltitle.fragment.BaseFragment;
import com.example.horizontalscrolltitle.layout.HorizontalTabList;
import com.example.horizontalscrolltitle.layout.HorizontalTabList.OnItemSelectedListener;


public class MainActivity extends FragmentActivity implements OnPageChangeListener{
 
private List<String> mTitleList = new ArrayList<String>();
private List<BaseFragment> mFragmentList = new ArrayList<BaseFragment>();
private ViewPager mViewPager;
private FragmentAdapter mAdapter;
private HorizontalTabList mHorizontalTabList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);


mViewPager            = (ViewPager) findViewById(R.id.viewPager);
mHorizontalTabList    = (HorizontalTabList) findViewById(R.id.title);
loadData();
}


private void loadData(){//添加数据
for(int i = 1; i < 19; i ++){
mTitleList.add("第   " + i + "   个 tab");
}

mHorizontalTabList.setTabList(new OnItemSelectedListener() {

@Override
public void onItemSelected(int position) {
if(mViewPager != null){
mViewPager.setCurrentItem(position);
}
}
}, mTitleList);

for(int i = 0; i < mTitleList.size(); i ++){
BaseFragment baseFragment = new BaseFragment(mTitleList.get(i));
mFragmentList.add(baseFragment);
}

mAdapter = new FragmentAdapter(getSupportFragmentManager(), mFragmentList);
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(this);
mHorizontalTabList.setCurrentPosition(0);
}


private class FragmentAdapter extends FragmentPagerAdapter{


private List<BaseFragment> mFragments;
public FragmentAdapter(FragmentManager fm, List<BaseFragment> fragments) {
super(fm);
mFragments = fragments;
}


@Override
public Fragment getItem(int arg0) {
return mFragments.get(arg0);
}


@Override
public int getCount() {
return mFragments.size();
}

}




@Override
public void onPageScrollStateChanged(int arg0) {
}


@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}


@Override
public void onPageSelected(int arg0) {
mViewPager.setCurrentItem(arg0);
mHorizontalTabList.setCurrentPosition(arg0);
}


}

4.工具类



//用于dp转px

package com.example.horizontalscrolltitle.utils;


import android.content.Context;


public class DisplayUtils {


public static int dp2px(Context context, double dp){
float density = context.getResources().getDisplayMetrics().density;
int px = (int) (dp * density + 0.5f);
return px;
}
}



//用于加载布局

package com.example.horizontalscrolltitle.utils;


import android.app.Activity;
import android.view.View;


public class LayoutInflateUtils {


public static View inflate(Activity activity, int resId){
if(activity != null){
return activity.getLayoutInflater().inflate(resId, null);
}
return null;
}
}


5.资源

(1).tab_bg_normal.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@color/color_tab_bg"/>


</shape>

(2).tab_bg_pressed.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
   
    
    <item android:drawable="@color/color_text_selected" />
    
    <item android:bottom="2dp" >
        <shape > 
            <solid android:color="@color/color_tab_bg"/>
        </shape>
    </item>
    
</layer-list>

(3).tab_bg_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/tab_bg_pressed" android:state_selected="true"/>
    <item android:drawable="@drawable/tab_bg_normal" />


</selector>

(4).tab_textcolor_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    
    <item android:color="@color/color_text_selected" android:state_selected="true"></item>
    
    <item android:color="@color/color_text_normal" ></item>


</selector>

(5)fragment_base_layout.xml

<?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:gravity="center">
    
<TextView android:id="@+id/textview"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:textSize="18sp"
   android:text="fragment"/>
    
</LinearLayout>

(6)tab的布局 tab_layout.xml

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout android:layout_width="wrap_content"
        android:layout_height="match_parent"
        xmlns:android="http://schemas.android.com/apk/res/android">
        
        <TextView 
       android:id="@+id/tab"
   android:layout_width="wrap_content"
   android:layout_height="48dp"
   android:layout_margin="1dp"
   android:background="@drawable/tab_bg_selector"
   android:textColor="@drawable/tab_textcolor_selector"
   android:textSize="16sp"
   android:gravity="center"
   android:paddingLeft="7.5dp"
   android:paddingRight="7.5dp"/>
        
    </LinearLayout>
    
    

(7)colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    
    <color name="color_text_selected">#FFFFFF</color>
    <color name="color_text_normal">#8B8386</color>
    <color name="color_tab_bg">#FF7F24</color>
    <color name="color_line">#66CDAA</color>
    <color name="color_gray">#CCCCCC</color>
    
</resources>


    


1
0

猜你在找
【直播】机器学习&数据挖掘7周实训--韦玮
【套餐】系统集成项目管理工程师顺利通关--徐朋
【直播】3小时掌握Docker最佳实战-徐西宁
【套餐】机器学习系列套餐(算法+实战)--唐宇迪
【直播】计算机视觉原理及实战--屈教授
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之矩阵--黄博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之凸优化--马博士
【套餐】Javascript 设计模式实战--曾亮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:20592次
    • 积分:566
    • 等级:
    • 排名:千里之外
    • 原创:35篇
    • 转载:2篇
    • 译文:0篇
    • 评论:6条
    最新评论