【问题标题】:create and set margin programmatic for relative layout android为相对布局android创建和设置边距编程
【发布时间】:2013-10-20 22:59:40
【问题描述】:

您好,我正在开发 android 应用程序,在该应用程序中我正在以编程方式创建相对布局,并尝试为此设置边距并将其添加到具有线性方向的线性布局中。 所以这是我的代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/screen_background"
    tools:context=".ChooseChannelsFragment" >

    <LinearLayout 
      android:id="@+id/main_outer_llt"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:orientation="horizontal"
      >

  </LinearLayout> 

</RelativeLayout>

在片段内部,我正在添加这样的相对布局

RelativeLayout relativeLayout = new RelativeLayout(getActivity());
    RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(200, 80);
    relativeParams.setMargins(20, 20, 20, 20);
    relativeLayout.setLayoutParams(relativeParams);
    relativeLayout.setBackgroundColor(getResources().getColor(R.color.green_color));
    linearLayout.addView(relativeLayout);

它创建具有给定颜色和大小但不接受边距的布局。难道我做错了什么?这个怎么做?需要帮忙。谢谢。

【问题讨论】:

标签: android android-relativelayout margins


【解决方案1】:

在这种情况下,父亲是LinearLayout。所以你应该使用:

TableLayout.LayoutParams layoutParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(20, 20, 20, 20);

【讨论】:

  • 但这适用于表格布局,适用于相对布局吗?
【解决方案2】:

您在视图上使用的 LayoutParams 类型实际上应该来自其父级。

因此,如果您将 RelativeLayout 添加到 LinearLayout,则设置为 RelativeLayout 的 LayoutParams 实际上应该是 LinearLayout.LayourParams,而不是 RelativeLayout.LayoutParams。

【讨论】:

    【解决方案3】:

    正如其他人所建议的,layout_margin# 是父级的 # 边缘和您的视图之间的空间。

    • # 替换“左”、“右”、“上”或“下”

    获取/设置边距对我有用:

    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mView.getLayoutParams();
    params.topMargin += 20;
    mView.requestLayout(); // important
    

    当然,我的 View 确实是一个 ViewGroup,而父级也是一个 ViewGroup。在大多数情况下,您应该将布局参数转换为父视图类的 LayoutParams(在本例中是 ViewGroup 和 RelativeLayout)

    【讨论】:

      猜你喜欢
      • 2017-02-25
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      • 2016-02-24
      相关资源
      最近更新 更多