圆角Tablayout以及仿微信QQ小红点,数字通知

最近在项目中遇到类似微信或者QQ那样的通知小红点,还要有数字通知,当数字大于99时显示99+。看到网上很多朋友提到用BadgeView(github上有),自己也用了下,发现虽然不错但是还是有点不足。后来又有个功能用到如图所示的Tablayout,


在github上找到了FlycoTabLayout这个开源的项目,不仅满足了市面上大多数Tablayout的UI,还封装了小红点和数字通知的功能,于是把其中具有代表性的几个功能实现在自己的Demo上,最后实现的效果是这个样子的,


废话好像有点多了下面开始进入主题。

FlycoTabLayout这个库里关于Tablayout的设计形式有很多,这里我仅使用了其中的一种SegmentTablayout。SegmentTablayout和Google官方提供的Tablayout不一样,没有定义与ViewPager关联起来的方法。所以我在使用的时候需要给它设置选中监听。

这部分的布局文件很简单:

<com.flyco.tablayout.SegmentTabLayout
        android:id="@+id/mtablayout"
        android:layout_width="match_parent"
        android:layout_height="32dp"
        android:layout_gravity="center_horizontal"
        android:layout_margin="10dp"
        tl:tl_bar_color="#ffffff"
        tl:tl_indicator_color="#2C97DE"
        tl:tl_indicator_corner_radius="8dp"
        tl:tl_tab_padding="20dp"
        />
    <android.support.v4.view.ViewPager
        android:id="@+id/mviewpager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

 

程序部分代码:
private String[] mTitles = {"警告","通知","推荐"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tabLayout = (SegmentTabLayout) findViewById(R.id.mtablayout);
        viewPager = (ViewPager) findViewById(R.id.mviewpager);
        fragments.add(new PagerOne());
        fragments.add(new PagerTwo());
        fragments.add(new PagerThree());
        tabLayout.setTabData(mTitles);//给Tablayout设置标题
		
	viewPager.setAdapter(new MyPagerAdpater(getSupportFragmentManager()));
        //为tablayout设置选中监听
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

  //同时,还要给Viewpager设置选中监听,才能使SegmentTablayout和ViewPager双向同步。
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int
                    positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });   
至于Adapter的代码就是灰常简单了。
 private class MyPagerAdpater extends FragmentPagerAdapter {
        public MyPagerAdpater(FragmentManager fm) {
            super(fm);
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }
    }
这样就形成了文章最开始贴的图片的Tab样式了,并且Viewpager随便滑,Tab随便点。

下面开始说小红点,在FlycoTabLayout中定义了一个小红点的封装类——MsgView。当要添加小红点的时候,我们只需要在布局文件中把它加上就好了,下面先说我在顶部Toolbar上的99+小红点,布局文件代码如下:

<android.support.v7.widget.Toolbar
        android:id="@+id/azure_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="#0065bd">
        <RelativeLayout android:layout_width="wrap_content"
                        android:layout_height="wrap_content">
            <ImageButton
                android:id="@+id/notification"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@android:color/transparent"
                android:src="@android:drawable/ic_menu_add"/>
            <com.flyco.tablayout.widget.MsgView
                android:id="@+id/msgview"
                xmlns:mv="http://schemas.android.com/apk/res-auto"
                android:layout_toRightOf="@id/notification"
                android:gravity="center"
                android:textColor="#ffffff"
                android:textSize="11.5sp"
                android:visibility="gone"
                mv:mv_backgroundColor="#FD481F"
                mv:mv_isRadiusHalfHeight="true"
                mv:mv_strokeColor="#ffffff"
                mv:mv_strokeWidth="1dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </RelativeLayout>

        <TextView android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_gravity="center_horizontal"
                  android:text="Tablayout"
                  android:textColor="#ffffff"
                  android:textSize="16sp"/>
    </android.support.v7.widget.Toolbar>
MsgView定义了三种红点的显示方式:1.没有数字的,就单纯显示个点。2.数字在1-99的,显示实际数字。3.数字大于99的,显示99+。

我们在Toolbar上的99+,实际上就一行代码的事儿。

{
            //添加未读消息,带数字未读红点。其实就是在布局文件中写好了
            msgView = (MsgView) findViewById(R.id.msgview);
            UnreadMsgUtils.show(msgView,666);
        }
Tab上通知的小红点呢,不要我们写布局文件和其他方法, SegmentTablayout都给我们封装好了,我们只需要调用SegmentTablayout.showDot(position)方法就行了。

当然,还没有结束,我底部红点就和这些不一样了,底部我采用的是RadioGroup和RadioButton的方式,如果直接在需要显示红点的地方加上MsgView,会不显示,那怎么办呢?这时候就需要我们自己定义一个RadioGroup,让它继承LinearLayout,这样就可以了。

public class NestRadioGroup extends LinearLayout {
    // holds the checked id; the selection is empty by default
    private int mCheckedId = -1;
    // tracks children radio buttons checked state
    private CompoundButton.OnCheckedChangeListener mChildOnCheckedChangeListener;
    // when true, mOnCheckedChangeListener discards events
    private boolean mProtectFromCheckedChange = false;
    private OnCheckedChangeListener mOnCheckedChangeListener;
    private PassThroughHierarchyChangeListener mPassThroughListener;

    /**
     * {@inheritDoc}
     */
    public NestRadioGroup(Context context) {
        super(context);
        init();
    }

    /**
     * {@inheritDoc}
     */
    public NestRadioGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mCheckedId = View.NO_ID;
        setOrientation(HORIZONTAL);
        mChildOnCheckedChangeListener = new CheckedStateTracker();
        mPassThroughListener = new PassThroughHierarchyChangeListener();
        super.setOnHierarchyChangeListener(mPassThroughListener);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) {
        // the user listener is delegated to our pass-through listener
        mPassThroughListener.mOnHierarchyChangeListener = listener;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        // checks the appropriate radio button as requested in the XML file
        if (mCheckedId != View.NO_ID) {
            mProtectFromCheckedChange = true;
            setCheckedStateForView(mCheckedId, true);
            mProtectFromCheckedChange = false;
            setCheckedId(mCheckedId);
        }
    }

    /** 递归查找具有选中属性的子控件 */
    private static CompoundButton findCheckedView(View child) {
        if (child instanceof CompoundButton)
            return (CompoundButton) child;
        if (child instanceof ViewGroup) {
            ViewGroup group = (ViewGroup) child;
            for (int i = 0, j = group.getChildCount(); i < j; i++) {
                CompoundButton check = findCheckedView(group.getChildAt(i));
                if (check != null)
                    return check;
            }
        }
        return null;//没有找到
    }

    @Override
    public void addView(View child, int index, ViewGroup.LayoutParams params) {
        final CompoundButton view = findCheckedView(child);
        if (view != null) {
            if (view.isChecked()) {
                mProtectFromCheckedChange = true;
                if (mCheckedId != -1) {
                    setCheckedStateForView(mCheckedId, false);
                }
                mProtectFromCheckedChange = false;
                setCheckedId(view.getId());
            }
        }
        super.addView(child, index, params);
    }

    /**
     * <p>Sets the selection to the radio button whose identifier is passed in
     * parameter. Using -1 as the selection identifier clears the selection;
     * such an operation is equivalent to invoking {@link #clearCheck()}.</p>
     *
     * @param id the unique id of the radio button to select in this group
     *
     * @see #getCheckedRadioButtonId()
     * @see #clearCheck()
     */
    public void check(int id) {
        // don't even bother
        if (id != -1 && (id == mCheckedId)) {
            return;
        }

        if (mCheckedId != -1) {
            setCheckedStateForView(mCheckedId, false);
        }

        if (id != -1) {
            setCheckedStateForView(id, true);
        }

        setCheckedId(id);
    }

    private void setCheckedId(int id) {
        mCheckedId = id;
        if (mOnCheckedChangeListener != null) {
            mOnCheckedChangeListener.onCheckedChanged(this, mCheckedId);
        }
    }

    private void setCheckedStateForView(int viewId, boolean checked) {
        View checkedView = findViewById(viewId);
        if (checkedView != null && checkedView instanceof CompoundButton) {
            ((CompoundButton) checkedView).setChecked(checked);
        }
    }

    /**
     * <p>Returns the identifier of the selected radio button in this group.
     * Upon empty selection, the returned value is -1.</p>
     *
     * @return the unique id of the selected radio button in this group
     *
     * @see #check(int)
     * @see #clearCheck()
     *
     * @attr ref android.R.styleable#NestRadioGroup_checkedButton
     */
    public int getCheckedRadioButtonId() {
        return mCheckedId;
    }

    /**
     * <p>Clears the selection. When the selection is cleared, no radio button
     * in this group is selected and {@link #getCheckedRadioButtonId()} returns
     * null.</p>
     *
     * @see #check(int)
     * @see #getCheckedRadioButtonId()
     */
    public void clearCheck() {
        check(-1);
    }

    /**
     * <p>Register a callback to be invoked when the checked radio button
     * changes in this group.</p>
     *
     * @param listener the callback to call on checked state change
     */
    public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
        mOnCheckedChangeListener = listener;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new NestRadioGroup.LayoutParams(getContext(), attrs);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
        return p instanceof NestRadioGroup.LayoutParams;
    }

    @Override
    protected LinearLayout.LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    }

    /**
     * <p>This set of layout parameters defaults the width and the height of
     * the children to {@link #WRAP_CONTENT} when they are not specified in the
     * XML file. Otherwise, this class ussed the value read from the XML file.</p>
     *
     * <p>See
     * {@link android.R.styleable#LinearLayout_Layout LinearLayout Attributes}
     * for a list of all child view attributes that this class supports.</p>
     *
     */
    public static class LayoutParams extends LinearLayout.LayoutParams {
        /**
         * {@inheritDoc}
         */
        public LayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
        }

        /**
         * {@inheritDoc}
         */
        public LayoutParams(int w, int h) {
            super(w, h);
        }

        /**
         * {@inheritDoc}
         */
        public LayoutParams(int w, int h, float initWeight) {
            super(w, h, initWeight);
        }

        /**
         * {@inheritDoc}
         */
        public LayoutParams(ViewGroup.LayoutParams p) {
            super(p);
        }

        /**
         * {@inheritDoc}
         */
        public LayoutParams(MarginLayoutParams source) {
            super(source);
        }

        /**
         * <p>Fixes the child's width to
         * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} and the child's
         * height to  {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}
         * when not specified in the XML file.</p>
         *
         * @param a the styled attributes set
         * @param widthAttr the width attribute to fetch
         * @param heightAttr the height attribute to fetch
         */
        @Override
        protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {

            if (a.hasValue(widthAttr)) {
                width = a.getLayoutDimension(widthAttr, "layout_width");
            } else {
                width = WRAP_CONTENT;
            }

            if (a.hasValue(heightAttr)) {
                height = a.getLayoutDimension(heightAttr, "layout_height");
            } else {
                height = WRAP_CONTENT;
            }
        }
    }

    /**
     * <p>Interface definition for a callback to be invoked when the checked
     * radio button changed in this group.</p>
     */
    public interface OnCheckedChangeListener {
        /**
         * <p>Called when the checked radio button has changed. When the
         * selection is cleared, checkedId is -1.</p>
         *
         * @param group the group in which the checked radio button has changed
         * @param checkedId the unique identifier of the newly checked radio button
         */
        public void onCheckedChanged(NestRadioGroup group, int checkedId);
    }

    private class CheckedStateTracker implements CompoundButton.OnCheckedChangeListener {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // prevents from infinite recursion
            if (mProtectFromCheckedChange) {
                return;
            }

            mProtectFromCheckedChange = true;
            if (mCheckedId != -1) {
                setCheckedStateForView(mCheckedId, false);
            }
            mProtectFromCheckedChange = false;

            int id = buttonView.getId();
            setCheckedId(id);
        }
    }

    /**
     * <p>A pass-through listener acts upon the events and dispatches them
     * to another listener. This allows the table layout to set its own internal
     * hierarchy change listener without preventing the user to setup his.</p>
     */
    private class PassThroughHierarchyChangeListener implements ViewGroup.OnHierarchyChangeListener {
        private ViewGroup.OnHierarchyChangeListener mOnHierarchyChangeListener;

        /**
         * {@inheritDoc}
         */
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
        public void onChildViewAdded(View parent, View child) {
            if (parent == NestRadioGroup.this) {
                CompoundButton view = findCheckedView(child);//查找子控件
                if (view != null) {
                    int id = view.getId();
                    // generates an id if it's missing
                    if (id == View.NO_ID && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        id = View.generateViewId();
                        view.setId(id);
                    }
                    view.setOnCheckedChangeListener(mChildOnCheckedChangeListener);
                }
            }

            if (mOnHierarchyChangeListener != null) {
                mOnHierarchyChangeListener.onChildViewAdded(parent, child);
            }
        }

        /**
         * {@inheritDoc}
         */
        public void onChildViewRemoved(View parent, View child) {
            if (parent == NestRadioGroup.this) {
                CompoundButton view = findCheckedView(child);//查找子控件
                if (view != null) {
                    view.setOnCheckedChangeListener(null);
                }
            }

            if (mOnHierarchyChangeListener != null) {
                mOnHierarchyChangeListener.onChildViewRemoved(parent, child);
            }
        }
    }
}
这时候我们在布局文件中把MsgView加上就可以了。为了不使文章过长,就只粘含有MagView的RadioButton了。

 <com.example.v_lzhiy.tablayout.view.NestRadioGroup
        android:id="@+id/radioGroup_bottom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#f9f9f9"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:padding="5dp"
        >
        <RelativeLayout android:layout_width="0dp"
                        android:layout_weight="1"
                        android:layout_height="wrap_content">
            <RadioButton
                android:id="@+id/rb_azure"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:background="@android:color/transparent"
                android:button="@android:color/transparent"
                android:drawableTop="@drawable/rb_me_selector"
                android:textSize="18sp"
                android:textColor="@drawable/bottom_radiobutton_selector"
                android:drawablePadding="1dp"
                android:gravity="center"
                android:text="Home"/>
            <com.flyco.tablayout.widget.MsgView
                android:id="@+id/msgview_azure"
                xmlns:mv="http://schemas.android.com/apk/res-auto"
                android:layout_toRightOf="@id/rb_azure"
                android:gravity="center"
                android:textColor="#ffffff"
                android:visibility="visible"
                mv:mv_backgroundColor="#FD481F"
                mv:mv_isRadiusHalfHeight="true"
                mv:mv_strokeColor="#ffffff"
                mv:mv_strokeWidth="1dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </RelativeLayout>

这时候我们再调用UnreadMsgUtils.show(msgView,0);就可以了。但是会发现,这个红点有点小啊,怎么把它变大呢? 虽然 UnreadMsgUtils有提供setSize方法,但是用起来好像没卵用,为什么呢?看看源码就知道了。所以要改变红点的大小需要我们自己写show方法,其实也很简单,只需要把show方法中控制红点宽高的属性调整下就好。我是这样调整的:

radioGroup = (NestRadioGroup) findViewById(R.id.radioGroup_bottom);
            msgView_bottom = (MsgView) findViewById(R.id.msgview_azure);
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) msgView_bottom.getLayoutParams();
            DisplayMetrics dm = msgView_bottom.getResources().getDisplayMetrics();
            msgView_bottom.setVisibility(View.VISIBLE);
            msgView_bottom.setStrokeWidth(0);
            msgView_bottom.setText("");

                lp.width = (int) (10 * dm.density);//这里从6变10
                lp.height = (int) (10 * dm.density);//这里从6变10
            msgView_bottom.setLayoutParams(lp);

就这样了,感谢 FlycoTabLayout开源项目(github地址:https://github.com/H07000223/FlycoTabLayout)和农民伯伯的支持内部嵌套布局的RadioGroup。(农民伯伯: http://over140.cnblogs.com)
第一次写博客,如果有好的见解的话多多交流,欢迎提建议,O(∩_∩)O谢谢!

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
微信小程序中设置边框圆角,你可以通过以下方法实现: 1. 使用内联样式(style)设置边框圆角。在对应的组件上使用style属性,并设置border-radius样式来实现圆角效果。例如,如果你想给一个view组件添加圆角边框,可以设置以下样式: ```html <view style="border-radius: 10px; border: 1px solid #000000;">内容</view> ``` 这样就给view组件添加了10像素的圆角边框。 2. 使用外部样式表(wxss)设置边框圆角。首先,在对应的组件标签上添加一个class属性,例如: ```html <view class="rounded-border">内容</view> ``` 然后,在小程序的样式文件(wxss)中定义.rounded-border类的样式,如下所示: ```css .rounded-border { border-radius: 10px; border: 1px solid #000000; } ``` 这样就给view组件添加了10像素的圆角边框。 3. 使用小程序自带的组件样式类。微信小程序提供了一些组件样式类,可以直接在组件上使用,来实现一些常见的样式效果。例如,想给一个view组件添加圆角边框,可以直接在view组件上添加一个radius类,如下所示: ```html <view class="radius">内容</view> ``` 然后,在小程序的样式文件(wxss)中定义.radius类的样式,如下所示: ```css .radius { border-radius: 10px; } ``` 这样就给view组件添加了10像素的圆角。 以上是在微信小程序中设置边框圆角的几种方法,你可以根据实际需求选择适合你的方式进行设置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值