Yêu cầu thg 3 29, 2018 2:48 SA 1365 1 1
  • 1365 1 1
0

Thắc mắc về LinearLayout và RelativeLayout

Chia sẻ
  • 1365 1 1

Mình có 2 layout như sau :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorAccent"
        android:text="bcadcsad" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorAccent"
        android:text="bcadcsad" />
</RelativeLayout>

Mọi người có thể giải thích dùm mình vì sao khi dùng RelativeLayout thì TextView full màn hình còn khi dùng LinearLayout TextView có kích thước bằng kích thước text của nó không ?

LinearLayout

LinearLayout

RelativeLayout

RelativeLayout

1 CÂU TRẢ LỜI


Đã trả lời thg 3 30, 2018 4:27 SA
+5

Đầu tiên cần phải hiểu rằng thằng RelativeLayout nó là 1 layout mà các thằng child của nó đc xác định vị trí thông qua mối quan hệ giữa các child vs child hoặc child với parent

Note that you cannot have a circular dependency between the size of the RelativeLayout and the position of its children. For example, you cannot have a RelativeLayout whose height is set to WRAP_CONTENT and a child set to ALIGN_PARENT_BOTTOM

Nghĩa là mình không thể tạo ra một sự phụ thuộc lặp về kích thước giữa cha và con của nó. Ở ví dụ bạn đưa ra ở đây thằng cha đang bị phụ thuộc vào thằng con là chỗ là height của nó wrap_content đồng thời thằng con height = match_parent, vì kích thước, vị trí dựa vào mối quan hệ giữa parent và child mà ở đây nó phụ thuộc lẫn nhau trong size child và parent chưa cái nào dc xác định cả, nó như 1 vòng lặp vô hạn phụ thuộc nên sẽ sẽ full màn hình

  • Để giải quyết thì bạn phải set size height cho hoăc parent hoặc child, hoặc có thể để cả 2 height= wrap_content
Chia sẻ
Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí