为什么在Android中只有部分背景颜色发生变化?

时间:2018-09-23 13:58:59

标签: android android-layout android-studio

我正在关注youtube中的一些教程,并且学习了如何使用android:background = "#006699"添加背景色。但是,我意识到当我使用此代码时,仿真器屏幕的只有一部分会变色。看起来像这样 enter image description here

这是我的content_main.xml代码

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background = "#006699"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:layout_editor_absoluteY="137dp"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="160dp"
        android:layout_marginStart="160dp"
        android:layout_marginTop="244dp"
        android:text="TextView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

仅在文本框着色之前。为什么会这样?预先感谢!

3 个答案:

答案 0 :(得分:5)

您的布局为wrap_contentandroid:layout_width设置了android:layout_height值。您应该改用match_parent值。

wrap_content使布局根据子元素的大小自行调整大小。

另一方面,

match_parent使其完全扩展到其父级的最大可用大小。在这种情况下,当它是根布局时,要扩展到整个可用空间。

答案 1 :(得分:1)

ConstraintLayoutmatch_parentwrap_content的高度和宽度。

 android:layout_width="match_parent"
 android:layout_height="match_parent"

答案 2 :(得分:1)

尝试如下修改

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"