【问题标题】:How to set layout property from code如何从代码中设置布局属性
【发布时间】:2011-07-31 15:24:36
【问题描述】:

如何设置 TextView 的属性,该属性位于代码中的 RelativeLayout 下。

这是我的布局:

<RelativeLayout
    android:id="@+id/team_left"
    android:layout_width="wrap_content"
    android:layout_height="50dip"
    android:layout_alignParentLeft="true">
    <ImageView
        android:id="@+id/flag_left"     
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/img"/>
    <TextView
        android:id="@+id/country_left"
        android:textColor="@color/txt_color"  
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>

如何从代码中为 textview 设置“android:layout_toRightOf="@id/flag_left" 等属性。

【问题讨论】:

  • 如何访问该布局?是您设置为内容视图的布局,还是使用充气器对其进行充气?
  • 布局是在活动 oncreate 上设置的。我将布局设置为内容视图

标签: android layout textview android-relativelayout params


【解决方案1】:

您需要为 textview 使用 RelativeLayout.LayoutParams,然后使用 addRule

例子:

RelativeLayout.LayoutParams params =
    new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
                                    LayoutParams.FILL_PARENT);
params.addRule(RelativeLayout.LAYOUT_ABOVE, R.id.flag_left);
tv.setLayoutParams(params);

【讨论】:

  • RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); params.addRule(android.R.attr.layout_above, R.id.flag_left); tv.setLayoutParams(params);
  • 谢谢。我要试试这个。
  • params.addRule(RelativeLayout.CENTER_VERTICAL, 1);它没有按预期工作。我做错什么了吗!?
  • RelativeLayout.CENTER_VERTICAL 将不起作用。您需要使用android.R.attr.layout_centerVertical 更多价值请查看此表developer.android.com/reference/android/R.attr.html
猜你喜欢
  • 1970-01-01
  • 2011-06-06
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
  • 2011-06-29
  • 1970-01-01
相关资源
最近更新 更多