高仿今日头条(1)

本片博客主要实现今日头条的主题框架。后面我会慢慢完善,欢迎大家持续关注

git下载地址:https://github.com/xiangzhihong/topNews/tree/master

先上两张图

直接贴代码:

 @InjectView(android.R.id.tabcontent)
    FrameLayout tabcontent;
    @InjectView(android.R.id.tabs)
    TabWidget tabs;
    @InjectView(R.id.tabhost)
    TabHost tabHost;
    @InjectView(R.id.tab_home)
    RadioButton tabHome;
    @InjectView(R.id.tab_video)
    RadioButton tabVideo;
    @InjectView(R.id.tab_topic)
    RadioButton tabTopic;
    @InjectView(R.id.tab_mine)
    RadioButton tabMine;

    private Intent topic;
    private Intent video;
    private Intent news;
    private Intent mine;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        flagBarTint(false);
        setContentView(R.layout.activity_tabhost);
        ButterKnife.inject(this);
//        UIUtil.initTintMgr(this, tabs).setStatusBarTintColor(getResources().getColor(R.color.c9));
        init(savedInstanceState);
    }

    private void init(Bundle savedInstanceState) {
        LocalActivityManager groupActivity = new LocalActivityManager(this,
                false);
        groupActivity.dispatchCreate(savedInstanceState);
        tabHost.setup(groupActivity);
        initIntent();
        addSpec();
        ((RadioGroup) findViewById(R.id.tab_radiogroup))
                .setOnCheckedChangeListener(this);
    }

    private void initIntent() {
        news = new Intent(this, NewsActivity.class);
        video = new Intent(this, VideoActivity.class);
        topic = new Intent(this, TopicActivity.class);
        mine = new Intent(this, MineActivity.class);
    }

    private void addSpec() {
        tabHost.addTab(this.buildTagSpec("home", R.string.xinwen,
                R.drawable.home_selector, news));
        tabHost.addTab(this.buildTagSpec("video", R.string.video,
                R.drawable.video_selector, video));
        tabHost.addTab(this.buildTagSpec("topic", R.string.topic,
                R.drawable.topic_selector, topic));
        tabHost.addTab(this.buildTagSpec("mine", R.string.me, R.drawable.mine_selector,
                mine));
    }

    private TabHost.TabSpec buildTagSpec(String tagName, int string, int icon,
                                         Intent content) {
        return tabHost
                .newTabSpec(tagName)
                .setIndicator(getResources().getString(string),
                        getResources().getDrawable(icon)).setContent(content);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.tab_home:
                tabHost.setCurrentTabByTag("home");
                setCurrentChecked(tabHome);
                break;
            case R.id.tab_video:
                tabHost.setCurrentTabByTag("video");
                setCurrentChecked(tabVideo);
                break;
            case R.id.tab_topic:
                tabHost.setCurrentTabByTag("topic");
                setCurrentChecked(tabTopic);
                break;
            case R.id.tab_mine:
                tabHost.setCurrentTabByTag("mine");
                setCurrentChecked(tabMine);
                break;
        }
    }

    private void setCurrentChecked(RadioButton currentTab) {
        tabHome.setTextColor(getResources().getColor(R.color.c6));
        tabVideo.setTextColor(getResources().getColor(R.color.c6));
        tabTopic.setTextColor(getResources().getColor(R.color.c6));
        tabMine.setTextColor(getResources().getColor(R.color.c6));

        currentTab.setTextColor(getResources().getColor(R.color.c9));
    }

    boolean doubleBackToExitPressedOnce = false;

    @Override
    public void onBackPressed() {
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed();
            return;
        }
        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "再按一次退出网易新闻", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    }

主要看一下我自己封装的TabStrip,

public class TabStrip extends HorizontalScrollView {
    public interface IconTabProvider {
        public int getPageIconResId(int position);
    }

    private static final int[] ATTRS = new int[]{
            android.R.attr.textSize,
            android.R.attr.textColor
    };
    private LinearLayout.LayoutParams defaultTabLayoutParams;
    private LinearLayout.LayoutParams expandedTabLayoutParams;

    private final PageListener pageListener = new PageListener();
    public OnPageChangeListener delegatePageListener;

    private LinearLayout tabsContainer;
    private ViewPager pager;
    private int tabCount;
    private int currentPosition = 0;
    private int tabCurrentPosition=0;
    private float currentPositionOffset = 0f;
    private Paint rectPaint;

    private int indicatorColor = 0xFF666666;
    private int underlineColor = 0x1A000000;
    private int tabTextColor = 0xFF666666;
    private int tabCheckTextColor = 0xFF666666;
    private boolean shouldExpand = false;
    private int scrollOffset = 52;
    private int indicatorHeight = 8;
    private int underlineHeight = 2;
    private int tabPadding = 20;
    private int tabTextSize = 14;
    private Typeface tabTypeface = null;
    private int tabTypefaceStyle = Typeface.BOLD;
    private int lastScrollX = 0;
    private Locale locale;


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

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

    public TabStrip(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setFillViewport(true);
        setWillNotDraw(false);
        tabsContainer = new LinearLayout(context);
        tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
        tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        addView(tabsContainer);

        DisplayMetrics dm = getResources().getDisplayMetrics();

        scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm);
        indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm);
        underlineHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm);
        tabPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm);
        tabTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm);
        TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);
        tabTextSize = a.getDimensionPixelSize(0, tabTextSize);
        tabTextColor = a.getColor(0, tabTextColor);
        a.recycle();

        a = context.obtainStyledAttributes(attrs, R.styleable.TabStrip);
        indicatorColor = a.getColor(R.styleable.TabStrip_indicatorLineColor, indicatorColor);
        underlineColor = a.getColor(R.styleable.TabStrip_underlineColor, underlineColor);
        tabCheckTextColor = a.getColor(R.styleable.TabStrip_tabCheckTextColor, tabTextColor);
        tabTextSize = a.getDimensionPixelSize(R.styleable.TabStrip_tabTextSize, tabTextSize);
        indicatorHeight = a.getDimensionPixelSize(R.styleable.TabStrip_indicatorHeight, indicatorHeight);
        underlineHeight = a.getDimensionPixelSize(R.styleable.TabStrip_underlineHeight, underlineHeight);
        tabPadding = a.getDimensionPixelSize(R.styleable.TabStrip_tabPaddingLeftRight, tabPadding);
        shouldExpand = a.getBoolean(R.styleable.TabStrip_shouldExpand, shouldExpand);
        scrollOffset = a.getDimensionPixelSize(R.styleable.TabStrip_scrollOffset, scrollOffset);
        a.recycle();
        rectPaint = new Paint();
        rectPaint.setAntiAlias(true);
        rectPaint.setStyle(Paint.Style.FILL);

        defaultTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f);

        if (locale == null) {
            locale = getResources().getConfiguration().locale;
        }
    }

    public void setViewPager(ViewPager pager) {
        this.pager = pager;
        if (pager.getAdapter() == null) {
            throw new IllegalStateException("ViewPager does not have adapter instance.");
        }
        pager.setOnPageChangeListener(pageListener);
        notifyDataSetChanged();
    }

    public void setOnPageChangeListener(OnPageChangeListener listener) {
        this.delegatePageListener = listener;
    }

    public void notifyDataSetChanged() {
        tabsContainer.removeAllViews();
        tabCount = pager.getAdapter().getCount();
        for (int i = 0; i < tabCount; i++) {
            if (pager.getAdapter() instanceof IconTabProvider) {
                addIconTab(i, ((IconTabProvider) pager.getAdapter()).getPageIconResId(i));
            } else {
                addTextTab(i, pager.getAdapter().getPageTitle(i).toString());
            }
        }
        updateTabStyles();
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }

                currentPosition = pager.getCurrentItem();
                scrollToChild(currentPosition, 0);
            }
        });

    }

    private void addTextTab(final int position, String title) {
        TextView tab = new TextView(getContext());
        tab.setText(title);
        tab.setGravity(Gravity.CENTER);
        tab.setSingleLine();
        addTab(position, tab);
    }

    private void addIconTab(final int position, int resId) {
        ImageButton tab = new ImageButton(getContext());
        tab.setImageResource(resId);
        addTab(position, tab);
    }

    private void addTab(final int position, View tab) {
        tab.setFocusable(true);
        tab.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                pager.setCurrentItem(position);
            }
        });

        tab.setPadding(tabPadding, 0, tabPadding, 0);
        tabsContainer.addView(tab, position, shouldExpand ? expandedTabLayoutParams : defaultTabLayoutParams);
    }

    private void updateTabStyles() {
        for (int i = 0; i < tabCount; i++) {
            View v = tabsContainer.getChildAt(i);
            if (v instanceof TextView) {
                TextView tab = (TextView) v;
                tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize);
                tab.setTypeface(tabTypeface, tabTypefaceStyle);
                if (i==currentPosition){
                    tab.setTextColor(tabCheckTextColor);
                }else {
                    tab.setTextColor(tabTextColor);
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                    tab.setAllCaps(true);
                } else {
                    tab.setText(tab.getText().toString().toUpperCase(locale));
                }
            }
        }

    }

    private void scrollToChild(int position, int offset) {
        if (tabCount == 0) {
            return;
        }
        int newScrollX = tabsContainer.getChildAt(position).getLeft() + offset;
        if (position > 0 || offset > 0) {
            newScrollX -= scrollOffset;
        }
        if (newScrollX != lastScrollX) {
            lastScrollX = newScrollX;
            scrollTo(newScrollX, 0);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (isInEditMode() || tabCount == 0) {
            return;
        }
        final int height = getHeight();
        rectPaint.setColor(indicatorColor);
        View currentTab = tabsContainer.getChildAt(currentPosition);
        float lineLeft = currentTab.getLeft();
        float lineRight = currentTab.getRight();
        if (currentPositionOffset > 0f && currentPosition < tabCount - 1) {
            View nextTab = tabsContainer.getChildAt(currentPosition + 1);
            final float nextTabLeft = nextTab.getLeft();
            final float nextTabRight = nextTab.getRight();

            lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
            lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);
        }
        canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint);

//		rectPaint.setColor(underlineColor);
//		canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint);

    }

    private class PageListener implements OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            currentPosition = position;
            currentPositionOffset = positionOffset;
            updateTabStyles();
            scrollToChild(position, (int) (positionOffset * tabsContainer.getChildAt(position).getWidth()));
            invalidate();
            if (delegatePageListener != null) {
                delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_IDLE) {
                scrollToChild(pager.getCurrentItem(), 0);
            }
            if (delegatePageListener != null) {
                delegatePageListener.onPageScrollStateChanged(state);
            }
        }

        @Override
        public void onPageSelected(int position) {
            if (delegatePageListener != null) {
                delegatePageListener.onPageSelected(position);
            }
        }
    }


    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState savedState = (SavedState) state;
        super.onRestoreInstanceState(savedState.getSuperState());
        currentPosition = savedState.currentPosition;
        requestLayout();
    }

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState savedState = new SavedState(superState);
        savedState.currentPosition = currentPosition;
        return savedState;
    }

    static class SavedState extends BaseSavedState {
        int currentPosition;

        public SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            currentPosition = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            dest.writeInt(currentPosition);
        }

        public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }

然后在我们使用的地方只需要剪短的代码就好了。

 <xzh.com.wangyinews.view.TabStrip
             android:id="@+id/tabstrip"
             android:layout_width="wrap_content"
             android:layout_height="match_parent"
             app:indicatorLineColor="@color/c9"
             app:indicatorHeight="3px"
             app:underlineColor="@color/c3"
             app:tabTextSize="16sp"
             app:tabCheckTextColor="@color/c9"
             app:tabPaddingLeftRight="15dp"
             android:scrollbars="none"
             />

是不是很简单

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏ml

java学习之第五章编程题示例(初学篇)

1 /* 2 Animal.java 3 */ 4 package animal; 5 6 public abstract class Animal { ...

30910
来自专栏代码GG之家

android常用接口(二)

=图片========================== bitmap转Byte数组(微信分享就需要用到) public byte[] bmpToByteAr...

2208
来自专栏懒人开发

鸿洋AutoLayout代码分析(四):剩下的类

也和前面的AutoXXXLayout类似, 都只是通过 关联和依赖 AutoLayoutHelper , Override对应的 onMeasure(in...

1122
来自专栏Android小菜鸡

自定义广告图片轮播View——CarouselView

  因为一个广告机的需求,需要做一个广告轮播的效果,不需要什么特别的动画,正常的轮播就可以了。笔者看了网上很多文章,要么不好用,要么就是效果太多,太复杂,用不上...

1412
来自专栏向治洪

RecyclerView 实现横向滚动效果

我相信很久以前,大家在谈横向图片轮播是时候,优先会选择具有HorizontalScrollView效果和ViewPager来做,不过自从Google大会之后,系...

3956
来自专栏向治洪

Android侧滑删除另一种实现,SwipeListView补充

前不久在在做聊天删除功能的时候使用SwipeListView进行侧滑删除有一点小问题,因为SwipeListView嵌套在Fragment内的时候,会报一个转换...

1929
来自专栏代码GG之家

Android 开发常用接口

android常用接口 常见的一些调用接口 更多阅读全文后star,实时更、更新收集到的接口 dip转px public int convertDipO...

4688
来自专栏向治洪

仿微信聊天表情发送

如题,这是公司项目的一个功能模块,先上个效果图: ? 其次大致说说原理: 1,首先判断输入的字符,是否包含表情的文字,比如   ?  这个表情对应的文件名为 e...

5317
来自专栏web开发

JavaScript二维码生成——qrcode.js

在开发中,有时候,我们需要根据不同的内容来动态生成二维码,则可以使用qrcode.js这个小插件来实现。 1.qrcode.js文件内容: (1)未压缩(qrc...

2216
来自专栏林冠宏的技术文章

一行代码引入 ViewPager 无限循环 + 页码显示

(出处:https://cloud.tencent.com/developer/user/1148436/activities) 前序:   网上的这类 Vie...

5707

扫码关注云+社区