Android中的tabLayout中的重复选项卡

问题描述:

当我单击该选项卡时,当前选项卡的底部会创建一个重复的自定义图标。如何摆脱这一点?Android中的tabLayout中的重复选项卡

我使用下面的代码设置自定义标题:

private void setIcon(String title, int icon, boolean isSelected, int position) { 

     LinearLayout tab = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.custom_tab, null); 
     TextView tabTitle = (TextView) tab.findViewById(R.id.tab_title); 
     final CircleImageView tabImage = (CircleImageView) tab.findViewById(R.id.tab_image); 

     if (isSelected){ 
      //add shadow to image. 
      tabImage.setBorderColor(ContextCompat.getColor(getActivity(),R.color.white)); 
      tabImage.setBorderWidth(10); 
     } 

     Glide.with(getContext()).load(icon).into(tabImage); 

     tabTitle.setText(title); 
     tabLayout.getTabAt(position).setCustomView(tab); 
    } 

我所试图做的事: 当标签用户点击添加图像的外部边界。因此,要做到这一点,我在下面的tablayout加入addTabSelectedListener:

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { 
      @Override 
      public void onTabSelected(TabLayout.Tab tab) { 

       //add shadow on selected tab 
       setIcon(getTitle(tab.getPosition()), getIcon(tab.getPosition()),true,tab.getPosition()); 
      } 

      @Override 
      public void onTabUnselected(TabLayout.Tab tab) { 

       //remove shadow from previous tab 
       setIcon(getTitle(tab.getPosition()), getIcon(tab.getPosition()),false,tab.getPosition()); 

      } 

      @Override 
      public void onTabReselected(TabLayout.Tab tab) { 


      } 
     }); 

但新标签图标的正下方旧图标,而不是取代旧的图标添加。

我曾尝试:

  1. 使用tabLayout.removeTab(标签)
  2. 使用tabLayout.removeTabAt的(tab.getpostion());
  3. 使用tabLayout.removeAllTabs();

所有它们都导致NullPointerException。

编辑:

作为Arpan建议:

视图视图= tab.getCustomView(); 但我将如何从这个视图获取tabTitle和tabImage?

编辑2:

好吧,我能够做一些正确的部分,即图像加载正确,但标题显示在顶部移动的下面代替。

代码:

LinearLayout customTab = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.custom_tab, null); 
       final CircleImageView tabImage = (CircleImageView) tab.getCustomView().findViewById(R.id.tab_image); 
       final TextView tabTitle = (TextView) tab.getCustomView().findViewById(R.id.tab_title); 

       tabTitle.setText(getTitle(tab.getPosition())); 



       Glide.with(getContext()).load(getIcon(tab.getPosition())).into(tabImage); 

       tab.setCustomView(tabImage); 

如果我这样做,图像集完美,但标题进入它的顶部。我知道这是因为我没有在选项卡中设置tabTitle。我将如何做到这一点?

如果我使用线性布局并将其设置为比创建重复选项卡。

编辑3:

一切做完之后,我就呼吁tabtitle的setcustomViewAgain;

AFAIK每次在您的setIcon()方法中您正在创建一个新的标签视图实例。这似乎是问题所在。你应该做的是你应该从选项卡监听器传递视图并通过它来设置图标。

Yous应该通过选项卡。 getCustomView()作为您查看setIcon()功能并从该视图获取tabTitletabImage

编辑 让你的TextView的,你必须做你正在创建选项卡视图的新实例

tvTitle = (TextView)tab.getCustomView().findViewById(R.id.tab_title); 
+0

setIcon()来的方法。是tabLayout.getTabAt(position).setCustomView(tab);创建新的实例?我将如何从该视图获取tabTitle和tabImage? –

+0

这是查看哪个标签持有。你试过了吗? –

+0

看看更新后的答案 –