自定义视图未填满父视图

3
我有一个自定义视图,像这样:

我有一个自定义视图像这样

public class ButtonBar extends HorizontalScrollView
{
  public View mButtonRows;

  public ButtonBar(Context context, AttributeSet attrs)
  {
    super(context, attrs);
    LayoutInflater inflater = (LayoutInflater)
        context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mButtonRows = inflater.inflate(R.layout.toolbar, null);

    // button click handling code goes here

    addView(mButtonRows);
  }
}

这段代码包含在我的主XML文件中,如下:

<com.example.ButtonBar
  android:layout_width="fill_parent"
  android:layout_height="wrap_content" 
  android:layout_alignParentBottom="true"
  android:layout_below="@+id/pagecontent" />

并对像这样的xml文件进行扩展:
<LinearLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/ButtonsRow" 
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal">
  <Button 
    android:id="@+id/button1"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_weight="0.3"
    android:text="button1"
  />
  <Button 
    android:id="@+id/button2"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_weight="0.3"
    android:text="button2"
  />
  <Button 
    android:id="@+id/button3"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_weight="0.3"
    android:text="button3"
  />
</LinearLayout>

(它目前只有三个按钮,但是在以后的版本中需要更多的按钮,因此需要HorizontalScrollView。)在hierarchyviewer中查看,自定义视图似乎是屏幕宽度,但是LinearLayout仅包含其所包含的按钮宽度(当前按钮大小约为屏幕的2/3),尽管设置了fill_parent宽度;按钮不会拉伸。如果我将LinearLayout的背景设置为@android:drawable / bottom_bar(这是一个宽度为屏幕宽度的png),则按钮会正确调整大小;我意识到我可以通过创建自己的图像来匹配来做同样的事情,但如果可能的话,我宁愿不这样做。 我做错了什么? 如果我将HorizontalScollView更改为ScrollView,则可以正常工作。HSV是否不允许其子元素“fill_parent”? 在主xml中设置android:fillViewport =“true”即可解决问题!

所以,基本上,您在水平线上看到三个按钮,每个按钮占屏幕宽度的1/3? - Rajath
我应该看到那个。但实际上我看到的是三个默认宽度的按钮(即,就像我使用了“layout_width =”wrap_content“”一样),占据了大约2/3的屏幕空间。 - Ben Williams
2个回答

7
在主xml中设置android:fillViewport="true"即可解决问题!

这有点傻 - 实际上它是HorizontalScrollView参考中的头等大事,我只是完全错过了它,直到我阅读ScrollView以找出为什么一个有效而另一个无效。/o\ - Ben Williams

0

如果你改成这样,对于每个按钮,它是否有效?

android:layout_width="0px"
android:layout_weight="1"

很遗憾,它并没有。在Eclipse中,如果我在图形布局视图中查看按钮栏xml,我的版本和您的版本都会按预期拉伸以适应屏幕,但当按钮栏被拖入其他布局时,它就不行了。我肯定在某个地方做了一些愚蠢的事情,但我不知道是什么。 - Ben Williams

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接