【问题标题】:layout_width and layout_height布局宽度和布局高度
【发布时间】:2012-02-07 17:42:53
【问题描述】:

有什么办法可以避免将 layout_width 和 layout_height 参数添加到我的自定义视图中?我知道有一些内置的 android 视图您不必为其提供这些属性。

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    决定它是否可以/应该提供这些属性不是视图的责任。父 ViewGroup 规定这些属性是否是必需的。例如,TableRow 使它们成为可选的。其他布局(LinearLayout、FrameLayout 等)需要这些参数。

    【讨论】:

    • 我没有这么想过。既然如此,我该如何让父 ViewGroup 让 XML 说“嘿,这家伙不需要向我展示这些东西。”?
    【解决方案2】:

    您何时不想使用高度和宽度参数?我不确定,但我认为这会导致它们甚至不会出现在布局上?

    参考这里http://developer.android.com/guide/topics/ui/declaring-layout.html#layout-params

    【讨论】:

    • 很像表格,我不需要它们,因为父视图控制子视图的布局参数。所以我在 XML 中指定的属性根本不做任何事情。
    【解决方案3】:

    来自同一位 Reference Dave 建议。

    所有视图组都包含宽度和高度(layout_width 和 layout_height),并且每个视图都需要定义它们。许多 LayoutParams 还包括可选的边距和边框。

    看起来,你必须

    【讨论】:

    • TableRow ViewGroup 如何解决这个问题?
    • @NicholasRoge 我不知道ViewGroup,但它说它是abstract class (developer.android.com/reference/android/view/ViewGroup.html) 扩展它的类,然而,它们实现了layout_heightlayout_width
    • @NicholasRoge 但正如我所说,我不知道。例如,您可以定义一个 ViewGroup 并将其用作 xml 中的布局吗?我怀疑它..
    • @NicholasRoge 如果您希望父级安排自定义控件的宽度和高度,为什么不使用“match_parent”?
    【解决方案4】:

    如果您想要减少通用和冗余属性,那么您应该尝试样式化。

    开发者指南here.

    【讨论】:

    • 这不是我想要的减少。是拆除。他们根本不需要在那里。
    【解决方案5】:

    问题在于ViewGroup.LayoutParams.setBaseAttributes() 使用严格的getLayoutDimension(int, String)。 您需要扩展您需要的任何 LayoutParams 并覆盖 setBaseAttributes。 在里面你可以手动设置宽度和高度,或者使用更宽松的getLayoutDimension(int, int)。最后,您必须在使用自己的 LayoutParams 的布局类中覆盖。

       @Override
       public LayoutParams generateLayoutParams(AttributeSet attrs) {
           return new LayoutParams(getContext(), attrs);
       }
    
       public static class LayoutParams extends FrameLayout.LayoutParams {
           public LayoutParams(Context context, AttributeSet attrs) {
               super(context, attrs);
           }
    
          @Override
          protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
             width = a.getLayoutDimension(widthAttr, WRAP_CONTENT);
             height = a.getLayoutDimension(heightAttr, WRAP_CONTENT);
          }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多