2015-12-09 37 views
3

我在對話框中有一個簡單的佈局,其中AppCompat ToolbarTabLayout裏面。我希望我的標籤有圖標留下文字。Android:工具欄Tablayout,圖標在文本上方呈現

這是對話框的佈局。

<android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar" 
      android:layout_height="wrap_content" 
      android:layout_width="match_parent" 
      > 

     <android.support.design.widget.TabLayout 
       android:id="@+id/tabs" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       app:tabMode="fixed" 
       app:tabGravity="fill" 
       /> 
    </android.support.v7.widget.Toolbar> 

    <ListView 
      android:id="@+id/list" 
      android:layout_width="match_parent" 
      android:layout_height="fill_parent" 
      /> 
</LinearLayout> 

然後我編程方式添加的標籤。

tabs.addTab(tabs.newTab() 
       .setTag(SettingsTabTag) 
       .setText("Settings") 
       .setIcon(R.drawable.scan_tab_settings_black), true); 
tabs.addTab(tabs.newTab() 
       .setTag(MetadataTabTag) 
       .setText("Metadata") 
       .setIcon(R.drawable.scan_tab_metadata_black)); 

但圖標始終呈現文本和一個非常小的上方。

+0

你找到一個解決辦法? –

回答

2

1.創建一個自定義標籤佈局

<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/tab" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:textAlignment="center"/> 

2.IN您的活動設置的自定義選項卡

TextView newTab = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); 
newTab.setText("tab1"); //tab label txt 
newTab.setCompoundDrawablesWithIntrinsicBounds(your_drawable_icon_here, 0, 0, 0); 
tabLayout.getTabAt(tab_index_here_).setCustomView(newTab); 

setCompoundDrawablesWithIntrinsicBounds做的工作。

1

下面是通常用於使圖標位於標籤標題左側的代碼。

在我的情況下,我必須添加一個線性佈局中心tablayout標題。我還添加了一些空格字符以在圖標和文本之間獲得邊距。

custom_tab.xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:gravity="center"> 
    <TextView 
     android:id="@+id/tabContent" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:textAlignment="center" 
     android:textColor="@android:color/white" 
     android:gravity="center"/> 
</LinearLayout> 

初始化代碼:

LinearLayout tabLinearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); 
TextView tabContent = (TextView) tabLinearLayout.findViewById(R.id.tabContent); 
tabContent.setText(" "+getApplicationContext().getResources().getString(tabTitles[i])); 
tabContent.setCompoundDrawablesWithIntrinsicBounds(tabIcons[i], 0, 0, 0); 
mTabLayout.getTabAt(i).setCustomView(tabContent);