SupportMapFragment问题嵌套TabHost片段 [英] SupportMapFragment issue in nested TabHost Fragment

查看:191
本文介绍了SupportMapFragment问题嵌套TabHost片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有1 FragmentActivity 1主片段 2 tabshosted子片段一个是列表视图在地图另一回事。我这里有2个问题。第一个是,我有孩子的片段上的每个tabchanges prevent娱乐。第二个问题;我第一次点击选项卡在地图片段图中可以看出。但回来列出片段,并返回到地图片段的地图不被显示。我真的有麻烦,这部分在我的项目。我需要你的指导。我的所有code是如下。

主(父)片段

 公共类MainFragg扩展片段实现OnTabChangeListener {

    私人FragmentTabHost mTab​​Host;
    @覆盖
    公共查看onCreateView(LayoutInflater充气,@Nullable的ViewGroup容器,@Nullable捆绑savedInstanceState){
        查看rootView = inflater.inflate(R.layout.mainfragment,集装箱,假);

        mTabHost =(FragmentTabHost)rootView.findViewById(android.R.id.tabhost);
        mTabHost.setup(活性,getChildFragmentManager(),R.id.realtabcontent);

        mTabHost.addTab(mTabHost.newTabSpec(feedlist)setIndicator(分段表),FeedListFragment.class,空);
        mTabHost.addTab(mTabHost.newTabSpec(feedmap)setIndicator(片段映射),FeedMapFragment.class,空);
        mTabHost.setOnTabChangedListener(本);

        返回rootView;
    }
    公共无效onTabChanged(字符串tabId){

    }
}
 

儿童(名单)片段

 公共类FeedListFragment扩展片段{
    @覆盖
    公共查看onCreateView(LayoutInflater充气,@Nullable的ViewGroup容器,@Nullable捆绑savedInstanceState){
        查看rootView = inflater.inflate(R.layout.fragment_listfeed,集装箱,假);
        返回rootView;
    }
}
 

儿童(图)片段

 公共类FeedMapFragment扩展SupportMapFragment实现LocationListener的{

    公共FeedMapFragment(){

    }

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        initilizeMap();
    }
    GoogleMap的地图;
    @覆盖
    公共查看onCreateView(LayoutInflater充气,@Nullable的ViewGroup容器,@Nullable捆绑savedInstanceState){
        super.onCreateView(充气,容器,savedInstanceState);
        查看rootView = inflater.inflate(R.layout.fragment_feedmap,集装箱,假);

        如果(图== NULL)
            initilizeMap();

        返回rootView;
    }

    私人无效initilizeMap(){
        SupportMapFragment mSupportMapFragment =(SupportMapFragment)getFragmentManager()findFragmentById(R.id.mapwhere)。
      如果(mSupportMapFragment == NULL){
       FragmentManager fragmentManager = getFragmentManager();
       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
       mSupportMapFragment = SupportMapFragment.newInstance();
       fragmentTransaction.replace(R.id.mapwhere,mSupportMapFragment).commit();
         }
      如果(mSupportMapFragment!= NULL)
      {
       地图= mSupportMapFragment.getMap();
       如果(图!= NULL){
           map.setMyLocationEnabled(真正的); //为false表示禁用
            map.getUiSettings()setZoomControlsEnabled(假)。 // true表示启用
            map.getUiSettings()setCompassEnabled(真)。
            map.getUiSettings()setMyLocationButtonEnabled(真)。

            LocationManager locationManager =(LocationManager)getActivity()getSystemService(getActivity()LOCATION_SERVICE。)。
            locationManager.removeUpdates(本);
            标准标准=新标准();
            字符串商= locationManager.getBestProvider(标准,真正的);
            如果(供应商== NULL)
                onProviderDisabled(供应商);
            locationManager.requestLocationUpdates(提供商,0,0,这一点);
            位置位置= locationManager.getLastKnownLocation(供应商);
            map.moveCamera(CameraUpdateFactory.newLatLng(新经纬度(location.getLatitude(),location.getLongitude())));
            map.animateCamera(CameraUpdateFactory.zoomTo(12));
       }

      }
     }
}
 

我的主要活动

 公共类MainActivity扩展FragmentActivity {
    @覆盖
    保护无效的onCreate(包savedInstanceState){
         的setContentView(R.layout.mainactivity);

        FragmentTransaction英尺= getSupportFragmentManager()的BeginTransaction()。
         ft.replace(R.id.fragContainer,新MainFragg(),tabFrag);
    }
}
 

解决方案

我有完全一样的设置(地图和列表),我可以告诉你,这是非常痛苦的使用旧的标签式浏览模式的系统,我相信你。选项​​卡式导航模式操作栏已经pcated德$ P $。您应该使用FragmentPagerAdapter和SlidingTabLayout从目前的Andr​​oid样品。下面是关于这个问题的参考YT影片。在这个例子中可以调用列表/地图对象的地方。

PlacesCollectionTabsFragment.java - 实例化一个ViewPager两个片段

 公共类PlacesCollectionTabsFragment扩展片段{

静态最后弦乐LOG_TAG =PlacesCollectionTabsFragment;
私人SlidingTabLayout mSlidingTabLayout;
私人ViewPager mViewPager;

公共枚举TabTypes {
    列表(0),MAP(1);
    私人诠释MINDEX;
    私人TabTypes(INT指数){
        MINDEX =指数;
    }
    公众诠释getIndex(){
        返回MINDEX;
    }
}

公共静态PlacesCollectionTabsFragment instantiateWithSelectedTab(上下文的背景下,TabTypes tabType){
    返回instantiateWithSelectedTab(背景下,tabType,NULL);
}

公共静态PlacesCollectionTabsFragment instantiateWithSelectedTab(上下文的背景下,TabTypes tabType,捆绑参数){
    如果(tabType!= NULL){
        如果(参数== NULL)
            的args =新包();

        args.putInt(Constants.Args.PLACES_SELECTED_TAB,tabType.getIndex());
    }

    返程(PlacesCollectionTabsFragment)PlacesCollectionTabsFragment.instantiate(背景下,PlacesCollectionTabsFragment.class.getName(),参数);
}

@覆盖
公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
                         捆绑savedInstanceState){
    MainActivity活性=(MainActivity)getActivity();
    activity.getDrawerToggle()setDrawerIndicatorEnabled(真)。
    返回inflater.inflate(R.layout.fragment_tab_pager,集装箱,假);
}

@覆盖
公共无效onViewCreated(查看视图,捆绑savedInstanceState){
    mViewPager =(ViewPager)view.findViewById(R.id.viewpager);
    mViewPager.setAdapter(新PlacesDisplayTypePagerAdapter(getChildFragmentManager()));

    mSlidingTabLayout =(SlidingTabLayout)view.findViewById(R.id.sliding_tabs);
    mSlidingTabLayout.setViewPager(mViewPager);
    mSlidingTabLayout.setHostingFragment(本);
    mSlidingTabLayout.setSelectedIndicatorColors(getActivity()getResources()的getColor(R.color.pink));

    如果(getArguments()!= NULL)
    {
        INT currentTab = getArguments()调用getInt(Constants.Args.PLACE_SELECTED_TAB)。
        mViewPager.setCurrentItem(currentTab);
    }
}

类PlacesDisplayTypePagerAdapter扩展FragmentPagerAdapter {

    公共PlacesDisplayTypePagerAdapter(FragmentManager fragmentManager){
        超(fragmentManager);
    }

    @覆盖
    公众诠释getCount将(){
        返回2;
    }

    @覆盖
    公共CharSequence的getPageTitle(INT位置){
        开关(位置){
            情况下0:
                返回清单;
            情况1:
                返回地图;
            默认:
                返回清单;
        }
    }

    @覆盖
    公共片段的getItem(INT位置){
        如果(位置== 0){
            返回新PlacesListFragment();
        } 其他
            返回PlacesMapFragment.newInstance(getArguments());
    }

    @覆盖
    公共无效destroyItem(ViewGroup中的容器,INT位置,Object对象){
        container.removeView((查看)对象);
        Log.i(LOG_TAG,destroyItem()位置:+位置+]);
    }

}

公共无效onPageSelected(INT位置){
    MainActivity一个=(MainActivity)getActivity();
    开关(位置){
        情况下0:
            a.setTitle(地方名单);
            打破;
        情况1:
            a.setTitle(在地图上的位置);
            打破;
    }
}
}
 

fragment_tab_pager.xml

 < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:方向=垂直机器人:layout_width =match_parent
    机器人:layout_height =match_parent>

    < com.myapp.views.SlidingTabLayout
        机器人:ID =@ + ID / sliding_tabs
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT/>

    < android.support.v4.view.ViewPager
        机器人:ID =@ + ID / viewpager
        机器人:layout_width =match_parent
        机器人:layout_height =0px
        机器人:layout_weight =1
        机器人:背景=@机器人:彩色/白/>
< / LinearLayout中>
 

SlidingTabLayout.java - 接下来的两个类几乎等同于官方样片code

 公共类SlidingTabLayout扩展Horizo​​ntalScrollView {

私人PlacesCollectionTabsFragment mHostFragment;
公共无效setHostingFragment(PlacesCollectionTabsFragment placesCollectionTabsFragment){
    mHostFragment = placesCollectionTabsFragment;
}

/ **
 *允许完全控制选项卡中的布局绘制的颜色。设置有
 * {@link #setCustomTabColorizer(TabColorizer)}。
 * /
公共接口TabColorizer {

    / **
     返回:返回时,{@ code}位选择使用指示器的颜色。
     * /
    INT getIndicatorColor(INT位);

    / **
     返回:返回绘制的{@ code位置}右侧的分频器的颜色。
     * /
    INT getDividerColor(INT位);

}

私有静态最终诠释TITLE_OFFSET_DIPS = 24;
私有静态最终诠释TAB_VIEW_PADDING_DIPS = 16;
私有静态最终诠释TAB_VIEW_TEXT_SIZE_SP = 12;

私人诠释mTitleOffset;

私人诠释mTabViewLayoutId;
私人诠释mTabViewTextViewId;

私人ViewPager mViewPager;
私人ViewPager.OnPageChangeListener mViewPagerPageChangeListener;

私人最终SlidingTabStrip mTab​​Strip;

公共SlidingTabLayout(上下文的背景下){
    这(背景下,NULL);
}

公共SlidingTabLayout(上下文的背景下,ATTRS的AttributeSet){
    这(背景下,ATTRS,0);
}

公共SlidingTabLayout(上下文的背景下,ATTRS的AttributeSet,诠释defStyle){
    超(背景下,ATTRS,defStyle);

    //禁用滚动条
    setHorizo​​ntalScrollBarEnabled(假);
    //确保标签条填补了这一景观
    setFillViewport(真正的);

    mTitleOffset =(int)的(TITLE_OFFSET_DIPS * getResources()getDisplayMetrics()密度。);

    mTabStrip =新SlidingTabStrip(上下文);
    addView(mTabStrip,LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
}

/ **
 *设置自定义{@link TabColorizer}使用。
 *
 *如果您只需要简单的custmisation那么你可以使用
 * {@link #setSelectedIndicatorColors(INT ...)}和{@link #setDividerColors(INT ...)}实现
 *类似的效果。
 * /
公共无效setCustomTabColorizer(TabColorizer tabColorizer){
    mTabStrip.setCustomTabColorizer(tabColorizer);
}

/ **
 *设定用于指示所选择的选项卡的颜色。这些颜色被视为一个
 *圆阵。提供了一种颜色将意味着所有的标签都标有相同的颜色。
 * /
公共无效setSelectedIndicatorColors(INT ...颜色){
    mTabStrip.setSelectedIndicatorColors(颜色);
}

/ **
 *设置用于分隔标签的颜色。这些颜色被视为一个圆形阵列。
 *提供了一种颜色将意味着所有的标签都标有相同的颜色。
 * /
公共无效setDividerColors(INT ...颜色){
    mTabStrip.setDividerColors(颜色);
}

/ **
 *设置{@link android.support.v4.view.ViewPager.OnPageChangeListener}。当使用{@link SlidingTabLayout}你
 *必须通过这个方法来设置任意{@link android.support.v4.view.ViewPager.OnPageChangeListener}。这是这样
 *该布局可以更新它正确地滚动位置。
 *
 * @看到android.support.v4.view.ViewPager#setOnPageChangeListener(android.support.v4.view.ViewPager.OnPageChangeListener)
 * /
公共无效setOnPageChangeListener(ViewPager.OnPageChangeListener监听器){
    mViewPagerPageChangeListener =侦听器;
}

/ **
 *设置自定义布局被充气的标签视图。
 *
 *参数layoutResId布局ID被夸大
 *在{@link android.widget.TextView} @参数textViewId ID在放大视图
 * /
公共无效setCustomTabView(INT layoutResId,诠释textViewId){
    mTabViewLayoutId = layoutResId;
    mTabViewTextViewId = textViewId;
}

/ **
 *设置相关的观点寻呼机。需要注意的是这里的假设是,该寻呼机内容
 *(选项卡和选项卡标题的数量)并没有改变这一呼吁作出后。
 * /
公共无效setViewPager(ViewPager viewPager){
    mTabStrip.removeAllViews();

    mViewPager = viewPager;
    如果(viewPager!= NULL){
        viewPager.setOnPageChangeListener(新InternalViewPagerListener());
        populateTabStrip();
    }
}

/ **
 *创建要用于标签的默认视图。如果自定义选项卡视图不通过设置这就是所谓的
 * {@link #setCustomTabView(INT,INT)}。
 * /
受保护的TextView createDefaultTabView(上下文的背景下){
    TextView中的TextView =新的TextView(上下文);
    textView.setGravity(Gravity.CENTER);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,TAB_VIEW_TEXT_SIZE_SP);
    textView.setTypeface(Typeface.DEFAULT_BOLD);

    //设置标签占用整个屏幕宽度
    窗口管理WM =(窗口管理器)context.getSystemService(Context.WINDOW_SERVICE);
    显示显示= wm.getDefaultDisplay();
    点大小=新的点();
    如果(android.os.Build.VERSION.SDK_INT> = android.os.Build.VERSION_ codeS.HONEYCOMB_MR2){
        display.getSize(大小);
    }
    其他
    {
        size.set(display.getWidth(),display.getHeight());
    }
    textView.setWidth(size.x / 2);

    如果(Build.VERSION.SDK_INT> = Build.VERSION_ codeS.HONEYCOMB){
        //如果我们在蜂窝或更高版本正在运行,那么我们就可以用主题的
        // selectableItemBackground以确保查看有pressed状态
        的TypedValue outValue =新的TypedValue();
        的getContext()。getTheme()。resolveAttribute(android.R.attr.selectableItemBackground,
                outValue,真正的);
        textView.setBackgroundResource(outValue.resourceId);
    }

    如果(Build.VERSION.SDK_INT> = Build.VERSION_ codeS.ICE_CREAM_SANDWICH){
        //如果我们在ICS或更新正在运行,使全大写,以配合操作栏标签样式
        textView.setAllCaps(真正的);
    }

    INT填充=(int)的(TAB_VIEW_PADDING_DIPS * getResources()getDisplayMetrics()密度。);
    textView.setPadding(填充,填充,填充,填充);

    返回的TextView;
}

私人无效populateTabStrip(){
    最终PagerAdapter适配器= mViewPager.getAdapter();
    最后View.OnClickListener tabClickListener =新TabClickListener();

    的for(int i = 0; I< adapter.getCount();我++){
        查看TabView的= NULL;
        TextView的tabTitleView = NULL;

        如果(mTabViewLayoutId!= 0){
            //如果有一个自定义选项卡视图布局ID设置,尝试它充气
            TabView的= LayoutInflater.from(的getContext())。膨胀(mTabViewLayoutId,mTabStrip,
                    假);
            tabTitleView =(TextView中)tabView.findViewById(mTabViewTextViewId);
        }

        如果(TabView的== NULL){
            TabView的= createDefaultTabView(的getContext());
        }

        如果(tabTitleView == NULL和放大器;&安培; TextView.class.isInstance(TabView的)){
            tabTitleView =(TextView中)TabView的;
        }

        tabTitleView.setText(adapter.getPageTitle(ⅰ));
        tabView.setOnClickListener(tabClickListener);

        mTabStrip.addView(TabView的);
    }
}

@覆盖
保护无效onAttachedToWindow(){
    super.onAttachedToWindow();

    如果(mViewPager!= NULL){
        scrollToTab(mViewPager.getCurrentItem(),0);
    }
}

私人无效scrollToTab(INT的tabIndex,诠释positionOffset){
    最终诠释tabStripChildCount = mTab​​Strip.getChildCount();
    如果(tabStripChildCount == 0 ||的tabIndex℃,||的tabIndex> = tabStripChildCount){
        返回;
    }

    查看selectedChild = mTab​​Strip.getChildAt(的tabIndex);
    如果(selectedChild!= NULL){
        INT targetScrollX = selectedChild.getLeft()+ positionOffset;

        如果(的tabIndex大于0 || positionOffset大于0){
            //如果我们不是在第一个孩子,而且中间滚动,确保我们遵守偏移
            targetScrollX  -  = mTitleOffset;
        }

        scrollTo(targetScrollX,0);
    }
}

私有类InternalViewPagerListener实现ViewPager.OnPageChangeListener {
    私人诠释mScrollState;

    @覆盖
    公共无效onPageScrolled(INT位置,浮positionOffset,诠释positionOffsetPixels){
        INT tabStripChildCount = mTab​​Strip.getChildCount();
        如果((tabStripChildCount == 0)||(位置℃下)||(位置> = tabStripChildCount)){
            返回;
        }

        mTabStrip.onViewPagerPageChanged(位置,positionOffset);

        查看selectedTitle = mTab​​Strip.getChildAt(位置);
        INT extraOffset =(selectedTitle!= NULL)
                ? (中间体)(positionOffset * selectedTitle.getWidth())
                :0;
        scrollToTab(位置,extraOffset);

        如果(mViewPagerPageChangeListener!= NULL){
            mViewPagerPageChangeListener.onPageScrolled(位置,positionOffset,
                    positionOffsetPixels);
        }
    }

    @覆盖
    公共无效onPageScrollStateChanged(INT状态){
        mScrollState =状态;

        如果(mViewPagerPageChangeListener!= NULL){
            mViewPagerPageChangeListener.onPageScrollStateChanged(州);
        }
    }

    @覆盖
    公共无效onPageSelected(INT位置){
        如果(mScrollState == ViewPager.SCROLL_STATE_IDLE){
            mTabStrip.onViewPagerPageChanged(位置,0F);
            scrollToTab(位置,0);
        }

        如果(mViewPagerPageChangeListener!= NULL){
            mViewPagerPageChangeListener.onPageSelected(位置);
        }

        mHostFragment.onPageSelected(位置);
    }

}

私有类TabClickListener实现View.OnClickListener {
    @覆盖
    公共无效的onClick(视图v){
        的for(int i = 0; I< mTab​​Strip.getChildCount();我++){
            如果(ⅴ== mTab​​Strip.getChildAt(ⅰ)){
                mViewPager.setCurrentItem(ⅰ);
                返回;
            }
        }
    }
}

}
 

SlidingTabStrip.java

 类SlidingTabStrip扩展的LinearLayout {

私有静态最终诠释DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 2;
私有静态最后一个字节DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0X26;
私有静态最终诠释SELECTED_INDICATOR_THICKNESS_DIPS = 8;
私有静态最终诠释DEFAULT_SELECTED_INDICATOR_COLOR = 0xFF33B5E5;

私有静态最终诠释DEFAULT_DIVIDER_THICKNESS_DIPS = 1;
私有静态最后一个字节DEFAULT_DIVIDER_COLOR_ALPHA = 0x20的;
私有静态最终浮动DEFAULT_DIVIDER_HEIGHT = 0.5F;

私人最终诠释mBottomBorderThickness;
私人最终涂料mBottomBorderPaint;

私人最终诠释mSelectedIndicatorThickness;
私人最终涂料mSelectedIndicatorPaint;

私人最终诠释mDefaultBottomBorderColor;

私人最终涂料mDividerPaint;
私人最终浮动mDividerHeight;

私人诠释mSelectedPosition;
私人浮动mSelectionOffset;

私人SlidingTabLayout.TabColorizer mCustomTabColorizer;
私人最终SimpleTabColorizer mDefaultTabColorizer;

SlidingTabStrip(上下文的背景下){
    这(背景下,NULL);
}

SlidingTabStrip(上下文的背景下,ATTRS的AttributeSet){
    超(背景下,ATTRS);
    setWillNotDraw(假);

    最终浮动密度= getResources()getDisplayMetrics()密度。

    的TypedValue outValue =新的TypedValue();
    。context.getTheme()resolveAttribute(android.R.attr.colorForeground,outValue,真正的);
    最终诠释themeForegroundColor = outValue.data;

    mDefaultBottomBorderColor = setColorAlpha(themeForegroundColor,
            DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);

    mDefaultTabColorizer =新SimpleTabColorizer();
    mDefaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);
    mDefaultTabColorizer.setDividerColors(setColorAlpha(themeForegroundColor,
            DEFAULT_DIVIDER_COLOR_ALPHA));

    mBottomBorderThickness =(int)的(DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS *密度);
    mBottomBorderPaint =新的油漆();
    mBottomBorderPaint.setColor(mDefaultBottomBorderColor);

    mSelectedIndicatorThickness =(int)的(SELECTED_INDICATOR_THICKNESS_DIPS *密度);
    mSelectedIndicatorPaint =新的油漆();

    mDividerHeight = DEFAULT_DIVIDER_HEIGHT;
    mDividerPaint =新的油漆();
    mDividerPaint.setStrokeWidth((int)的(DEFAULT_DIVIDER_THICKNESS_DIPS *密度));
}

无效setCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer){
    mCustomTabColorizer = customTabColorizer;
    无效();
}

无效setSelectedIndicatorColors(INT ...颜色){
    //确保定制colorizer被删除
    mCustomTabColorizer = NULL;
    mDefaultTabColorizer.setIndicatorColors(颜色);
    无效();
}

无效setDividerColors(INT ...颜色){
    //确保定制colorizer被删除
    mCustomTabColorizer = NULL;
    mDefaultTabColorizer.setDividerColors(颜色);
    无效();
}

无效onViewPagerPageChanged(INT位置,浮positionOffset){
    mSelectedPosition =位置;
    mSelectionOffset = positionOffset;
    无效();
}

@覆盖
保护无效的OnDraw(帆布油画){
    最终诠释高度=的getHeight();
    最终诠释childCount = getChildCount();
    最终诠释dividerHeightPx =(INT)(Math.min(Math.max(0F,mDividerHeight),1F)*高);
    最后SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer!= NULL
            ? mCustomTabColorizer
            :mDefaultTabColorizer;

    //厚色强调下面的当前选择
    如果(childCount大于0){
        查看selectedTitle = getChildAt(mSelectedPosition);
        INT左= selectedTitle.getLeft();
        INT右= selectedTitle.getRight();
        INT颜色= tabColorizer.getIndicatorColor(mSelectedPosition);

        如果(mSelectionOffset> 0F&安培;&安培; mSelectedPosition≤(getChildCount() -  1)){
            INT nextColor = tabColorizer.getIndicatorColor(mSelectedPosition + 1);
            如果(颜色!= nextColor){
                颜色= blendColors(nextColor,颜色,mSelectionOffset);
            }

            //绘制选择中途在标签之间
            视图nextTitle = getChildAt(mSelectedPosition + 1);
            左=(int)的(mSelectionOffset * nextTitle.getLeft()+
                    (1.0F  -  mSelectionOffset)*左);
            右=(INT)(mSelectionOffset * nextTitle.getRight()+
                    (1.0F  -  mSelectionOffset)*权);
        }

        mSelectedIndicatorPaint.setColor(颜色);

        canvas.drawRect(左,高度 -  mSelectedIndicatorThickness吧,
                高度,mSelectedIndicatorPaint);
    }

    //沿整个底部边缘薄下划线
    canvas.drawRect(0,高度 -  mBottomBorderThickness,的getWidth(),身高,mBottomBorderPaint);

    在标题之间//垂直分割线
    INT separatorTop =(身高 -  dividerHeightPx)/ 2;
    的for(int i = 0; I< childCount  -  1;我++){
        查看孩子= getChildAt(我);
        mDividerPaint.setColor(tabColorizer.getDividerColor(ⅰ));
        canvas.drawLine(child.getRight(),separatorTop,child.getRight(),
                separatorTop + dividerHeightPx,mDividerPaint);
    }
}

/ **
 *设置的Alpha值{@ code颜色}是给定的{@ code字母}值。
 * /
私有静态诠释setColorAlpha(INT颜色,字节阿尔法){
    返回Color.argb(α,Color.red(颜色),Color.green(颜色),Color.blue(彩色));
}

/ **
 *混合{@ code颜色1}和{@ code COLOR2}使用给定的比例。
 *
 *其中融入了@参数比例。 1.0将返回{@ code颜色1},0.5将会给一个更融合,
 * 0.0将返回{@ code COLOR2}。
 * /
私有静态诠释blendColors(INT颜色1,INT颜色2,流通股比例){
    最终浮动inverseRation = 1F  - 比;
    浮动R =(Color.red(颜色1)*比例)+(Color.red(颜色2)* inverseRation);
    浮G =(Color.green(颜色1)*比例)+(Color.green(颜色2)* inverseRation);
    浮动B =(Color.blue(颜色1)*比例)+(Color.blue(颜色2)* inverseRation);
    返回Color.rgb((INT)R,(INT)克(INT)二);
}

私有静态类SimpleTabColorizer实现SlidingTabLayout.TabColorizer {
    私人INT [] mIndicatorColors;
    私人INT [] mDividerColors;

    @覆盖
    公众最终诠释getIndicatorColor(INT位置){
        返回mIndicatorColors [位置%mIndicatorColors.length]。
    }

    @覆盖
    公众最终诠释getDividerColor(INT位置){
        返回mDividerColors [位置%mDividerColors.length]。
    }

    无效setIndicatorColors(INT ...颜色){
        mIndicatorColors =颜色;
    }

    无效setDividerColors(INT ...颜色){
        mDividerColors =颜色;
    }
}
}
 

现在我们的实际标签式的内容,我不会进入名单的片段,你有你的问题看起来还行的初学者来说,只知道我的名单在这里被称为PlacesListFragment.java。而对于PlacesMapFragment,它太大了堆栈溢出这样的 这里是一个链接 ,最终我会把这个网上的地方:)重要PlacesMapFragment扩展了普通的旧片段,该SupportMapFragment是创建编程后,出现了一些有据可查的,在过去​​做的时候错误它通过XML。

fragment_places_map.xml,一个地方把自定义地图控件等。

 < RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
机器人:ID =@ + ID / map_layout
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:背景=@色/白
机器人:方向=垂直>

< RelativeLayout的
    机器人:ID =@ + ID /图
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent/>
< / RelativeLayout的>
 

最后,从你的活动,所有你需要做的就是实例化PlacesCollectionTabsFragment,是这样的:

 片段片段= PlacesCollectionTabsFragment.instantiateWithSelectedTab(mContext,PlacesCollectionTabsFragment.TabTypes.LIST);
fragmentManager.beginTransaction()代替(R.id.fragmentContainer,片段, fragment.getClass().getSimpleName()).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).commit();
 

I have 1 FragmentActivity 1 main fragment and 2 tabshosted child fragment one is for listview another for map. I have 2 problems here. First one is that I have to prevent recreation of child fragments on every tabchanges. Second problem; the first time I click tab for map fragment map can be seen. but coming back to list fragment and return to map fragment map is not being showed. I am really have trouble with this part in my project. I need your guide. My all code is as below.

Main(Parent) Fragment

public class MainFragg extends Fragment implements OnTabChangeListener{

    private FragmentTabHost mTabHost;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.mainfragment, container, false);

        mTabHost = (FragmentTabHost)rootView.findViewById(android.R.id.tabhost);
        mTabHost.setup(activity, getChildFragmentManager(), R.id.realtabcontent);

        mTabHost.addTab(mTabHost.newTabSpec("feedlist").setIndicator("Fragment List"), FeedListFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("feedmap").setIndicator("Fragment Map"), FeedMapFragment.class, null);
        mTabHost.setOnTabChangedListener(this);

        return rootView;
    }
    public void onTabChanged(String tabId) {

    }
}

Child (list) fragment

public class FeedListFragment extends Fragment{
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_listfeed, container, false); 
        return rootView;
    }
}

Child (map) fragment

public class FeedMapFragment extends SupportMapFragment implements LocationListener{

    public FeedMapFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initilizeMap();
    }
    GoogleMap map;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View rootView = inflater.inflate(R.layout.fragment_feedmap, container, false);

        if(map == null)
            initilizeMap();

        return rootView;
    }

    private void initilizeMap(){
        SupportMapFragment mSupportMapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapwhere);
      if (mSupportMapFragment == null) {
       FragmentManager fragmentManager = getFragmentManager();
       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
       mSupportMapFragment = SupportMapFragment.newInstance();
       fragmentTransaction.replace(R.id.mapwhere, mSupportMapFragment).commit();
         }
      if (mSupportMapFragment != null)
      {
       map = mSupportMapFragment.getMap();
       if (map != null){
           map.setMyLocationEnabled(true); // false to disable
            map.getUiSettings().setZoomControlsEnabled(false); // true to enable
            map.getUiSettings().setCompassEnabled(true);
            map.getUiSettings().setMyLocationButtonEnabled(true);

            LocationManager locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
            locationManager.removeUpdates(this);
            Criteria criteria = new Criteria();
            String provider = locationManager.getBestProvider(criteria, true);
            if (provider == null)
                onProviderDisabled(provider);
            locationManager.requestLocationUpdates(provider, 0, 0, this);
            Location location = locationManager.getLastKnownLocation(provider);
            map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
            map.animateCamera(CameraUpdateFactory.zoomTo(12));
       }

      }
     }
}

My main activity

public class MainActivity extends FragmentActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
         setContentView(R.layout.mainactivity);

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
         ft.replace(R.id.fragContainer, new MainFragg(), "tabFrag");
    }
}

解决方案

I've got exactly the same setup (a map and a list) and I can tell you it was very painful using the old tabbed navigation mode system which I believe you are. The tabbed nav mode for the action bar has been deprecated. You should use a FragmentPagerAdapter and a SlidingTabLayout from the current Android samples. Here is a reference YT video on the subject. For this example lets call the list / map objects 'Places'.

PlacesCollectionTabsFragment.java - instantiates the two fragments in a ViewPager.

public class PlacesCollectionTabsFragment extends Fragment {

static final String LOG_TAG = "PlacesCollectionTabsFragment";
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;

public enum TabTypes {
    LIST(0), MAP(1);
    private int mIndex;
    private TabTypes(int index) {
        mIndex = index;
    }
    public int getIndex() {
        return mIndex;
    }
}

public static PlacesCollectionTabsFragment instantiateWithSelectedTab(Context context, TabTypes tabType) {
    return instantiateWithSelectedTab(context, tabType, null);
}

public static PlacesCollectionTabsFragment instantiateWithSelectedTab(Context context, TabTypes tabType, Bundle args) {
    if(tabType != null) {
        if(args == null)
            args = new Bundle();

        args.putInt(Constants.Args.PLACES_SELECTED_TAB, tabType.getIndex());
    }

    return (PlacesCollectionTabsFragment) PlacesCollectionTabsFragment.instantiate(context, PlacesCollectionTabsFragment.class.getName(), args);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    MainActivity activity = (MainActivity)getActivity();
    activity.getDrawerToggle().setDrawerIndicatorEnabled(true);
    return inflater.inflate(R.layout.fragment_tab_pager, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
    mViewPager.setAdapter(new PlacesDisplayTypePagerAdapter(getChildFragmentManager()));

    mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
    mSlidingTabLayout.setViewPager(mViewPager);
    mSlidingTabLayout.setHostingFragment(this);
    mSlidingTabLayout.setSelectedIndicatorColors(getActivity().getResources().getColor(R.color.pink));

    if(getArguments() != null)
    {
        int currentTab = getArguments().getInt(Constants.Args.PLACE_SELECTED_TAB);
        mViewPager.setCurrentItem(currentTab);
    }
}

class PlacesDisplayTypePagerAdapter extends FragmentPagerAdapter {

    public PlacesDisplayTypePagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "List";
            case 1:
                return "Map";
            default:
                return "List";
        }
    }

    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return new PlacesListFragment();
        } else
            return PlacesMapFragment.newInstance(getArguments());
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
        Log.i(LOG_TAG, "destroyItem() [position: " + position + "]");
    }

}

public void onPageSelected(int position) {
    MainActivity a = (MainActivity)getActivity();
    switch (position){
        case 0:
            a.setTitle("List of places");
            break;
        case 1:
            a.setTitle("Places on map");
            break;
    }
}
}

fragment_tab_pager.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.myapp.views.SlidingTabLayout
        android:id="@+id/sliding_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1"
        android:background="@android:color/white"/>
</LinearLayout>

SlidingTabLayout.java - the next two classes are virtually identical to the official sample code.

public class SlidingTabLayout extends HorizontalScrollView {

private PlacesCollectionTabsFragment mHostFragment;
public void setHostingFragment(PlacesCollectionTabsFragment placesCollectionTabsFragment) {
    mHostFragment = placesCollectionTabsFragment;
}

/**
 * Allows complete control over the colors drawn in the tab layout. Set with
 * {@link #setCustomTabColorizer(TabColorizer)}.
 */
public interface TabColorizer {

    /**
     * @return return the color of the indicator used when {@code position} is selected.
     */
    int getIndicatorColor(int position);

    /**
     * @return return the color of the divider drawn to the right of {@code position}.
     */
    int getDividerColor(int position);

}

private static final int TITLE_OFFSET_DIPS = 24;
private static final int TAB_VIEW_PADDING_DIPS = 16;
private static final int TAB_VIEW_TEXT_SIZE_SP = 12;

private int mTitleOffset;

private int mTabViewLayoutId;
private int mTabViewTextViewId;

private ViewPager mViewPager;
private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;

private final SlidingTabStrip mTabStrip;

public SlidingTabLayout(Context context) {
    this(context, null);
}

public SlidingTabLayout(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    // Disable the Scroll Bar
    setHorizontalScrollBarEnabled(false);
    // Make sure that the Tab Strips fills this View
    setFillViewport(true);

    mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);

    mTabStrip = new SlidingTabStrip(context);
    addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}

/**
 * Set the custom {@link TabColorizer} to be used.
 *
 * If you only require simple custmisation then you can use
 * {@link #setSelectedIndicatorColors(int...)} and {@link #setDividerColors(int...)} to achieve
 * similar effects.
 */
public void setCustomTabColorizer(TabColorizer tabColorizer) {
    mTabStrip.setCustomTabColorizer(tabColorizer);
}

/**
 * Sets the colors to be used for indicating the selected tab. These colors are treated as a
 * circular array. Providing one color will mean that all tabs are indicated with the same color.
 */
public void setSelectedIndicatorColors(int... colors) {
    mTabStrip.setSelectedIndicatorColors(colors);
}

/**
 * Sets the colors to be used for tab dividers. These colors are treated as a circular array.
 * Providing one color will mean that all tabs are indicated with the same color.
 */
public void setDividerColors(int... colors) {
    mTabStrip.setDividerColors(colors);
}

/**
 * Set the {@link android.support.v4.view.ViewPager.OnPageChangeListener}. When using {@link SlidingTabLayout} you are
 * required to set any {@link android.support.v4.view.ViewPager.OnPageChangeListener} through this method. This is so
 * that the layout can update it's scroll position correctly.
 *
 * @see android.support.v4.view.ViewPager#setOnPageChangeListener(android.support.v4.view.ViewPager.OnPageChangeListener)
 */
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
    mViewPagerPageChangeListener = listener;
}

/**
 * Set the custom layout to be inflated for the tab views.
 *
 * @param layoutResId Layout id to be inflated
 * @param textViewId id of the {@link android.widget.TextView} in the inflated view
 */
public void setCustomTabView(int layoutResId, int textViewId) {
    mTabViewLayoutId = layoutResId;
    mTabViewTextViewId = textViewId;
}

/**
 * Sets the associated view pager. Note that the assumption here is that the pager content
 * (number of tabs and tab titles) does not change after this call has been made.
 */
public void setViewPager(ViewPager viewPager) {
    mTabStrip.removeAllViews();

    mViewPager = viewPager;
    if (viewPager != null) {
        viewPager.setOnPageChangeListener(new InternalViewPagerListener());
        populateTabStrip();
    }
}

/**
 * Create a default view to be used for tabs. This is called if a custom tab view is not set via
 * {@link #setCustomTabView(int, int)}.
 */
protected TextView createDefaultTabView(Context context) {
    TextView textView = new TextView(context);
    textView.setGravity(Gravity.CENTER);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
    textView.setTypeface(Typeface.DEFAULT_BOLD);

    //Set tabs to take up entire screen width
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    Point size = new Point();
    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
        display.getSize(size);
    }
    else
    {
        size.set(display.getWidth(), display.getHeight());
    }
    textView.setWidth(size.x / 2);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // If we're running on Honeycomb or newer, then we can use the Theme's
        // selectableItemBackground to ensure that the View has a pressed state
        TypedValue outValue = new TypedValue();
        getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
                outValue, true);
        textView.setBackgroundResource(outValue.resourceId);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // If we're running on ICS or newer, enable all-caps to match the Action Bar tab style
        textView.setAllCaps(true);
    }

    int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
    textView.setPadding(padding, padding, padding, padding);

    return textView;
}

private void populateTabStrip() {
    final PagerAdapter adapter = mViewPager.getAdapter();
    final View.OnClickListener tabClickListener = new TabClickListener();

    for (int i = 0; i < adapter.getCount(); i++) {
        View tabView = null;
        TextView tabTitleView = null;

        if (mTabViewLayoutId != 0) {
            // If there is a custom tab view layout id set, try and inflate it
            tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
                    false);
            tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
        }

        if (tabView == null) {
            tabView = createDefaultTabView(getContext());
        }

        if (tabTitleView == null && TextView.class.isInstance(tabView)) {
            tabTitleView = (TextView) tabView;
        }

        tabTitleView.setText(adapter.getPageTitle(i));
        tabView.setOnClickListener(tabClickListener);

        mTabStrip.addView(tabView);
    }
}

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();

    if (mViewPager != null) {
        scrollToTab(mViewPager.getCurrentItem(), 0);
    }
}

private void scrollToTab(int tabIndex, int positionOffset) {
    final int tabStripChildCount = mTabStrip.getChildCount();
    if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
        return;
    }

    View selectedChild = mTabStrip.getChildAt(tabIndex);
    if (selectedChild != null) {
        int targetScrollX = selectedChild.getLeft() + positionOffset;

        if (tabIndex > 0 || positionOffset > 0) {
            // If we're not at the first child and are mid-scroll, make sure we obey the offset
            targetScrollX -= mTitleOffset;
        }

        scrollTo(targetScrollX, 0);
    }
}

private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
    private int mScrollState;

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        int tabStripChildCount = mTabStrip.getChildCount();
        if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
            return;
        }

        mTabStrip.onViewPagerPageChanged(position, positionOffset);

        View selectedTitle = mTabStrip.getChildAt(position);
        int extraOffset = (selectedTitle != null)
                ? (int) (positionOffset * selectedTitle.getWidth())
                : 0;
        scrollToTab(position, extraOffset);

        if (mViewPagerPageChangeListener != null) {
            mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
                    positionOffsetPixels);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        mScrollState = state;

        if (mViewPagerPageChangeListener != null) {
            mViewPagerPageChangeListener.onPageScrollStateChanged(state);
        }
    }

    @Override
    public void onPageSelected(int position) {
        if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
            mTabStrip.onViewPagerPageChanged(position, 0f);
            scrollToTab(position, 0);
        }

        if (mViewPagerPageChangeListener != null) {
            mViewPagerPageChangeListener.onPageSelected(position);
        }

        mHostFragment.onPageSelected(position);
    }

}

private class TabClickListener implements View.OnClickListener {
    @Override
    public void onClick(View v) {
        for (int i = 0; i < mTabStrip.getChildCount(); i++) {
            if (v == mTabStrip.getChildAt(i)) {
                mViewPager.setCurrentItem(i);
                return;
            }
        }
    }
}

}

SlidingTabStrip.java

class SlidingTabStrip extends LinearLayout {

private static final int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 2;
private static final byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0x26;
private static final int SELECTED_INDICATOR_THICKNESS_DIPS = 8;
private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xFF33B5E5;

private static final int DEFAULT_DIVIDER_THICKNESS_DIPS = 1;
private static final byte DEFAULT_DIVIDER_COLOR_ALPHA = 0x20;
private static final float DEFAULT_DIVIDER_HEIGHT = 0.5f;

private final int mBottomBorderThickness;
private final Paint mBottomBorderPaint;

private final int mSelectedIndicatorThickness;
private final Paint mSelectedIndicatorPaint;

private final int mDefaultBottomBorderColor;

private final Paint mDividerPaint;
private final float mDividerHeight;

private int mSelectedPosition;
private float mSelectionOffset;

private SlidingTabLayout.TabColorizer mCustomTabColorizer;
private final SimpleTabColorizer mDefaultTabColorizer;

SlidingTabStrip(Context context) {
    this(context, null);
}

SlidingTabStrip(Context context, AttributeSet attrs) {
    super(context, attrs);
    setWillNotDraw(false);

    final float density = getResources().getDisplayMetrics().density;

    TypedValue outValue = new TypedValue();
    context.getTheme().resolveAttribute(android.R.attr.colorForeground, outValue, true);
    final int themeForegroundColor =  outValue.data;

    mDefaultBottomBorderColor = setColorAlpha(themeForegroundColor,
            DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);

    mDefaultTabColorizer = new SimpleTabColorizer();
    mDefaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);
    mDefaultTabColorizer.setDividerColors(setColorAlpha(themeForegroundColor,
            DEFAULT_DIVIDER_COLOR_ALPHA));

    mBottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
    mBottomBorderPaint = new Paint();
    mBottomBorderPaint.setColor(mDefaultBottomBorderColor);

    mSelectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density);
    mSelectedIndicatorPaint = new Paint();

    mDividerHeight = DEFAULT_DIVIDER_HEIGHT;
    mDividerPaint = new Paint();
    mDividerPaint.setStrokeWidth((int) (DEFAULT_DIVIDER_THICKNESS_DIPS * density));
}

void setCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer) {
    mCustomTabColorizer = customTabColorizer;
    invalidate();
}

void setSelectedIndicatorColors(int... colors) {
    // Make sure that the custom colorizer is removed
    mCustomTabColorizer = null;
    mDefaultTabColorizer.setIndicatorColors(colors);
    invalidate();
}

void setDividerColors(int... colors) {
    // Make sure that the custom colorizer is removed
    mCustomTabColorizer = null;
    mDefaultTabColorizer.setDividerColors(colors);
    invalidate();
}

void onViewPagerPageChanged(int position, float positionOffset) {
    mSelectedPosition = position;
    mSelectionOffset = positionOffset;
    invalidate();
}

@Override
protected void onDraw(Canvas canvas) {
    final int height = getHeight();
    final int childCount = getChildCount();
    final int dividerHeightPx = (int) (Math.min(Math.max(0f, mDividerHeight), 1f) * height);
    final SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer != null
            ? mCustomTabColorizer
            : mDefaultTabColorizer;

    // Thick colored underline below the current selection
    if (childCount > 0) {
        View selectedTitle = getChildAt(mSelectedPosition);
        int left = selectedTitle.getLeft();
        int right = selectedTitle.getRight();
        int color = tabColorizer.getIndicatorColor(mSelectedPosition);

        if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) {
            int nextColor = tabColorizer.getIndicatorColor(mSelectedPosition + 1);
            if (color != nextColor) {
                color = blendColors(nextColor, color, mSelectionOffset);
            }

            // Draw the selection partway between the tabs
            View nextTitle = getChildAt(mSelectedPosition + 1);
            left = (int) (mSelectionOffset * nextTitle.getLeft() +
                    (1.0f - mSelectionOffset) * left);
            right = (int) (mSelectionOffset * nextTitle.getRight() +
                    (1.0f - mSelectionOffset) * right);
        }

        mSelectedIndicatorPaint.setColor(color);

        canvas.drawRect(left, height - mSelectedIndicatorThickness, right,
                height, mSelectedIndicatorPaint);
    }

    // Thin underline along the entire bottom edge
    canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);

    // Vertical separators between the titles
    int separatorTop = (height - dividerHeightPx) / 2;
    for (int i = 0; i < childCount - 1; i++) {
        View child = getChildAt(i);
        mDividerPaint.setColor(tabColorizer.getDividerColor(i));
        canvas.drawLine(child.getRight(), separatorTop, child.getRight(),
                separatorTop + dividerHeightPx, mDividerPaint);
    }
}

/**
 * Set the alpha value of the {@code color} to be the given {@code alpha} value.
 */
private static int setColorAlpha(int color, byte alpha) {
    return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
}

/**
 * Blend {@code color1} and {@code color2} using the given ratio.
 *
 * @param ratio of which to blend. 1.0 will return {@code color1}, 0.5 will give an even blend,
 *              0.0 will return {@code color2}.
 */
private static int blendColors(int color1, int color2, float ratio) {
    final float inverseRation = 1f - ratio;
    float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
    float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
    float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
    return Color.rgb((int) r, (int) g, (int) b);
}

private static class SimpleTabColorizer implements SlidingTabLayout.TabColorizer {
    private int[] mIndicatorColors;
    private int[] mDividerColors;

    @Override
    public final int getIndicatorColor(int position) {
        return mIndicatorColors[position % mIndicatorColors.length];
    }

    @Override
    public final int getDividerColor(int position) {
        return mDividerColors[position % mDividerColors.length];
    }

    void setIndicatorColors(int... colors) {
        mIndicatorColors = colors;
    }

    void setDividerColors(int... colors) {
        mDividerColors = colors;
    }
}
}

Now for our actual tabbed content, I won't go into the list fragment, what you've got in your question looks okay for starters, just know my list here is called the PlacesListFragment.java. As for the PlacesMapFragment, it's too big for Stack Overflow so here is a link, eventually I'll put this online somewhere :) Importantly PlacesMapFragment extends a regular old Fragment, the SupportMapFragment is created programmatically, there has been several well documented bugs in the past when doing it via xml.

fragment_places_map.xml, a place to put custom map controls etc.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">

<RelativeLayout
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</RelativeLayout>

Finally from your activity all you need to do is instantiate the PlacesCollectionTabsFragment, something like this:

Fragment fragment = PlacesCollectionTabsFragment.instantiateWithSelectedTab(mContext, PlacesCollectionTabsFragment.TabTypes.LIST);
fragmentManager.beginTransaction().replace(R.id.fragmentContainer, fragment, fragment.getClass().getSimpleName()).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).commit();

这篇关于SupportMapFragment问题嵌套TabHost片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆