【问题标题】:setBackgroundColor(int color) and RelativeLayoutsetBackgroundColor(int color) 和 RelativeLayout
【发布时间】:2013-03-13 15:19:03
【问题描述】:

当我使用这个 XML 文件时...

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"

tools:context=".MainActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"        
    android:text="@string/hello_world" />

</RelativeLayout>

..我看到背景颜色环绕内容

http://img716.imageshack.us/img716/8225/rlayout.jpg

但是如果我用代码写这个RelativeLayout...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    RelativeLayout layout = new RelativeLayout(this);

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);


    layout.setBackgroundColor(Color.parseColor("#FF0000"));

    TextView text = new TextView(this);
    text.setText("Hello world");

    //Añado texto
    layout.addView(text);

    layout.setLayoutParams(params);

    setContentView(layout); 
}

...我看到背景颜色匹配父级而不是包装内容

http://img404.imageshack.us/img404/1427/rlayoutfull.jpg

有什么想法吗?

谢谢!

【问题讨论】:

    标签: android android-relativelayout background-color


    【解决方案1】:

    你永远不会设置布局参数:

    layout.setLayoutParams(params);
    

    我认为你应该放置:

    TextView text = new TextView(this);
    text.setText("Hello world");
    

    以及在设置布局参数之前您将添加到布局中的所有其他视图,否则将没有内容可环绕。

    编辑:

    设置后会发生什么:

    tried to replace between the two:
    
     RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
           RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    

    ?

    【讨论】:

    • 我得到相同的结果...我不明白为什么....因为我认为我的代码和 XML 文件是相同的 =S
    • 我忘记了“layout.setLayoutParams”!现在我尝试将 textview 添加到 RelativeLayout 然后将参数添加到 relativelayout 但我得到相同的结果:S
    • 同理,全屏为红色。我认为这没有任何效果,因为我尝试使用 300px 宽度和高度,而且我还看到所有屏幕都是红色的:S
    • 如果我使用 LinearLayout,然后将 relativelayout(及其参数和 textview)添加到 linearlayout,它就像 XML 文件一样工作。你明白为什么吗?
    • 我猜如果您的相对布局是您的根视图,那么布局参数的处理方式会有所不同。
    猜你喜欢
    • 2014-12-17
    • 1970-01-01
    • 2017-03-17
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多