【问题标题】:Custom view not filling parent自定义视图不填充父级
【发布时间】:2011-04-26 19:25:13
【问题描述】:

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

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>

(它目前只有三个按钮,但在以后的版本中将需要更多按钮,因此是 Horizo​​ntalScrollView。)

查看hierarchyviewer,自定义视图似乎是屏幕宽的,但LinearLayout 仅与它包含的按钮一样宽(当前按钮大小约为屏幕的2/3),尽管有fill_parent宽度设置;按钮不会拉伸。如果我将 LinearLayout 的背景设置为@android:drawable/bottom_bar(这是屏幕宽度的 png),则按钮会正确调整大小;我意识到我可以通过创建自己的图像来匹配来做同样的事情,但如果可能的话,我宁愿不这样做。

我做错了什么?


ETA:如果我将 Horizo​​ntalScollView 更改为 ScrollView,它可以正常工作。 HSV 是否只是不允许他们的孩子“fill_parent”?


ETA2:在主 xml 中设置 android:fillViewport="true" 修复了它!

【问题讨论】:

  • 那么,基本上,您会在水平线上看到三个按钮,每个按钮占据屏幕宽度的 1/3?
  • 我应该看到这一点。我实际看到的是三个默认宽度的按钮(即,好像我使用了layout_width="wrap_content")占据了大约 2/3 的屏幕。

标签: android xml layout


【解决方案1】:

在主 xml 中设置 android:fillViewport="true" 修复它!

【讨论】:

  • 这有点愚蠢——它实际上是 Horizo​​ntalScrollView 参考中最重要的东西,我只是完全错过了它,直到我通读 ScrollView 以找出为什么一个有效而另一个无效。 /o\
【解决方案2】:

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

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

【讨论】:

  • 遗憾的是,事实并非如此。在 Eclipse 中,如果我在图形布局视图中查看按钮栏 xml,我的版本和您的版本都会按预期拉伸以适应屏幕,但是当按钮栏被拉入其他布局时,它不会。我确定我一定只是在某个地方做了一些愚蠢的事情,但我不知道是什么。
猜你喜欢
  • 2015-02-02
  • 1970-01-01
  • 2015-06-28
  • 2013-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多