2015-12-09 39 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);