【问题标题】:There is no tab background attribute in the java code to change tab background dynamicallyjava代码中没有标签背景属性可以动态改变标签背景
【发布时间】:2017-03-13 17:24:47
【问题描述】:

如何通过 java 代码动态更改选项卡背景这是我的布局代码。如果我可以在 java 代码中获取 app:tabBackground="@drawable/tab_background" 那么我可以使用选择器通过选项卡选择的位置更改可绘制的背景,以获得所需的屏幕,如第一张图片,但我无法在任何地方找到它,请朋友们帮帮我

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

    <android.support.design.widget.TabLayout
        android:id="@+id/icon_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/toolbar_bg"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        app:tabBackground="@drawable/tab_background"
        app:tabIndicatorColor="@color/transparent"
        app:tabGravity="fill"
        app:tabMode="fixed" />


    <FrameLayout
        android:id="@+id/main_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

我需要像下面这样的布局

但是我得到了这个布局

【问题讨论】:

    标签: java android android-layout android-tabs android-tablayout


    【解决方案1】:

    您需要为OnTabSelectedListener 事件创建一个监听器,并为每个项目init..tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FFFFFF"));

    tabLayout.setSelectedTabIndicatorHeight((int) (2 * getResources().getDisplayMetrics().density));
    

    【讨论】:

      【解决方案2】:

      试试这个:

      tabLayout.getTabAt(1).setCustomView(R.drawable.your_layout);   //2nd position
      

      或者你也可以使用自定义布局视图

      tabLayout.getTabAt(1).setCustomView(R.layout.your_layout); 
      

      对于整体Tablayout 使用

      tabLayout.setBackground(ContextCompat.getDrawable(this, R.drawable.your_drawable));
      

      【讨论】:

      • 通过创建自定义布局如何管理未选中的标签背景
      • 如果您想管理选择取消选择状态,您需要一个可绘制的选择器...您正在询问特定位置背景programetically
      • 是的,我正在使用 select 来管理选择和取消选择状态,我需要以编程方式更改 app:tab 背景
      猜你喜欢
      • 2018-06-13
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多