2017-03-13 51 views
0

如何通過Java代碼動態更改選項卡背景這裏是我的佈局代碼如果我可以獲得應用程序:tabBackground =「@ drawable/tab_background 「在Java代碼的話,我可以能夠通過選擇得到像第一圖像所需的畫面通過選項卡選擇的位置來改變背景繪製的,但我不能找到它的任何地方,請幫助我的朋友在Java代碼中沒有選項卡背景屬性來動態更改選項卡背景

<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> 

我需要佈局像下面

enter image description here

但我得到這個佈局

enter image description here

回答

0

您需要創建爲OnTabSelectedListener事件偵聽器,併爲每個項目的init ... tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FFFFFF"));

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

它不工作,因爲我預計 – prominere

0

試試這個:

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)); 
+0

通過創建自定義佈局如何管理,如果未選中的選項卡背景 – prominere

+0

你想管理選擇取消選擇狀態你需要一個可繪製的選擇器...有問題你問特定的位置背景'programetically' – rafsanahmad007

+0

是的,我使用選擇管理選擇和取消選擇狀態,我需要更改應用程序:標籤背景編程式先生 – prominere