2011-09-11 147 views
0

计算选项卡宽度时不填充整个屏幕我有含有TabHost水平ScrollView内五个标签。我希望所有标签都具有相同尺寸,最小尺寸为83dp。如果第五个选项卡适合屏幕显示,则所有选项卡都会变宽以填充整个屏幕。以下是实现此目的的代码:TabHost根据屏幕宽度

int tabMinWidth = (int) (83 * density); 
int tabWidth = tabMinWidth 
int nrOfTabs = displayMetrics.widthPixels/tabMinWidth; 
if (nrOfTabs > 4) 
    tabWidth = displayMetrics.widthPixels/5; 
for(int i = 0; i < 5; i++) 
    tabHost.getTabWidget().getChildAt(i).getLayoutParams().width = tabWidth; 

基本上代码工作正常。但是,选项卡并未使用整个屏幕宽度。例如:五个选项卡与96PX不填充屏幕分辨率320x480在横向模式下(约20像素的未使用的空间),虽然96×5正好是480我如何才能提高代码,使标签确实填满整个屏幕?

UPDATE: 解决方案:我发现了约4-5%调整每个选项卡工作得很好:

tabWidth = (int) (tabWidth *1.04); 

更新2: 我想我找到原因问题。这些选项卡具有负右侧和左侧边距。考虑到这些利润率可以解决问题,并且TabHost恰好填满整个屏幕。

+0

是标签按钮之间有差距?这可能是20px – blessenm

+0

是的,这些标签之间存在细微差距,但我怀疑它们是未使用空间的原因。它们应该使TabHost变得更宽(宽度+间隙)而不是太小。我现在通过将tabWidth乘以1.04来解决问题。但是,这只是一个近似值,仍然需要改进。 – crnv

回答

0

也许使用按钮将工作。

当我使用的标签,我通常只是隐藏设置的Android能见度不见了tabwidget标签。

按钮并将其添加到充当标签按钮像

<?xml version="1.0" encoding="utf-8"?> 
<TabHost xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/tabhost" android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" 
     android:layout_height="fill_parent">   
     <FrameLayout android:id="@android:id/tabcontent" 
      android:layout_width="fill_parent" android:layout_height="0dip" 
      android:layout_weight="1.0"/> 
     <FrameLayout android:layout_width="fill_parent" 
      android:layout_height="wrap_content"> 
      <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:visibility="gone"/> 
      <LinearLayout android:layout_width="fill_parent" 
       android:layout_height="64dip"> 
       <Button android:layout_height="fill_parent" android:layout_width="0dip" 
        android:layout_weight="1.0" 
        android:background="@drawable/ic_tab_artists" 
        android:id="@+id/artist_id" android:onClick="tabHandler"/> 
       <Button android:layout_height="fill_parent" android:layout_width="0dip" 
        android:layout_weight="1.0" 
        android:background="@drawable/ic_tab_artists" 
        android:id="@+id/album_id" android:onClick="tabHandler"/> 
      </LinearLayout> 
     </FrameLayout> 
    </LinearLayout> 
</TabHost> 

,我添加一个按钮单击处理

public void tabHandler(View target){ 
    artistButton.setSelected(false); 
    albumButton.setSelected(false); 
    songButton.setSelected(false); 
    if(target.getId() == R.id.artist_id){ 
     tabHost.setCurrentTab(0); 
     artistButton.setSelected(true); 
    } else if(target.getId() == R.id.album_id){ 
     tabHost.setCurrentTab(1); 
     albumButton.setSelected(true); 
    } 
} 

这使得它更容易自定义标签按钮。你将需要尝试一下,因为我还没有真正尝试过horizo​​ntalscrollview中的选项卡。

+0

谢谢你的回答。但是,我不想自己处理这些标签。它只是为了我的目的矫枉过正。我将使用上述的近似值。 – crnv

1

您可以设置水平滚动条的android:fillViewport="true"