安卓TabLayout加小红点提示内容更新

来源:互联网 发布:oracle java api 编辑:程序博客网 时间:2024/06/05 14:14

安卓原生的android.support.design.widget.TabLayout,配合ViewPager已经很好用了,但是有时我们会在内容更新时,在tab标题右上方加上一个红点等标记此tab内容有更新时,就需要给原生的TabLayout设置你定义的布局,用法和原生的一样,只是在代码中设置一下TabLayout的布局。

1.自定义Tab样式布局,@drawable/shape_red_solid就是一个shape资源,一个实心红圆点

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_gravity="center"    android:orientation="horizontal">    <TextView        android:textSize="15sp"        android:id="@+id/tv_tab_title"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:gravity="center"        android:textColor="@color/color_text_a3" />    <ImageView        android:id="@+id/iv_tab_red"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:background="@drawable/shape_red_solid" /></LinearLayout>

2.在ViewPager适配器中写一个getTabView方法,获取自定义布局

 public View getTabView(int position) {     View tabView = LayoutInflater.from(mContext).inflate(R.layout.item_tab_layout, null);     TextView tabTitle = (TextView) tabView.findViewById(R.id.tv_tab_title);     tabTitle.setText(list_title.get(position));     return tabView;  }

3.在设置完ViewPager适配器后设置TabLayout,主要代码就是tabLayout.getTabAt(i).setCustomView(tabView) 设置tabLayout的布局

 //TabLayout加载viewpager tabLayout.setupWithViewPager(tab_viewpager); //设置小红点 for (int i = 0; i < tabLayout.getTabCount(); i++) {    View tabView = myAdapter.getTabView(i);     ImageView imageView= (ImageView) tabView.findViewById(R.id.iv_tab_red);    /**在这里判断每个TabLayout的内容是否有更新,来设置小红点是否显示**/     tabLayout.getTabAt(i).setCustomView(tabView);  }

4.由于自定义Tab布局后,tab切换后标题字体颜色变化失效,设置TabLayout的监听来设置字体颜色变化,设置TabLayout选中后小红点消失,根据自己的逻辑记录更新内容已读取。

 //设置tablayout的选中监听tabLayout.addOnTabSelectedListener(new MyTabSelectedListener());class MyTabSelectedListener implements TabLayout.OnTabSelectedListener{   @Override    public void onTabSelected(TabLayout.Tab tab) {        int position = tab.getPosition();        /**在这里记录TabLayout选中后内容更新已读标记**/        View customView = tab.getCustomView();         customView.findViewById(R.id.iv_tab_red).setVisibility(View.GONE);        TextView textView = (TextView) customView.findViewById(R.id.tv_tab_title);        textView.setTextColor(getResources().getColor(R.color.color_text_6));   }   @Override  public void onTabUnselected(TabLayout.Tab tab) {      View customView = tab.getCustomView();      TextView textView = (TextView) customView.findViewById(R.id.tv_tab_title);      textView.setTextColor(getResources().getColor(R.color.color_text_a3));  }  @Override  public void onTabReselected(TabLayout.Tab tab) {  }}
0 0
原创粉丝点击