簡體   English   中英

如何在另一個布局中嵌入布局?

[英]How to embed a layout inside another layout?

我想要一個類似於下圖的布局,其中 (2) 是 LinearLayout 而 (1) 是使這成為可能的任何東西。 例如想象(2)是一個按鈕配置,(1)是一些不同大小的文本,需要 go 圍繞(2)。

里面的小方塊(右下) 大方塊

即使有圖像演示,似乎人們也誤解了我的問題,(2)不在(1)之上:! 讓我添加一個更詳細的圖像,如下所示:

嵌入不在頂部

很簡單,你做過約束布局嗎? 試試這個。

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

   <androidx.constraintlayout.widget.ConstraintLayout
       android:layout_width="match_parent"
       android:layout_height="250dp">

      <ImageView
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:src="@mipmap/ic_launcher"
          app:layout_constraintBottom_toBottomOf="parent"
          app:layout_constraintEnd_toEndOf="parent"
          app:layout_constraintStart_toStartOf="parent"
          app:layout_constraintTop_toTopOf="parent" />


      <ImageView
          android:layout_width="80dp"
          android:layout_height="80dp"
          android:src="@mipmap/ic_launcher"
          app:layout_constraintBottom_toBottomOf="parent"
          app:layout_constraintEnd_toEndOf="parent"
          app:layout_constraintHorizontal_bias="1.0"
          app:layout_constraintStart_toStartOf="parent"
          app:layout_constraintTop_toTopOf="parent"
          app:layout_constraintVertical_bias="1.0" />


   </androidx.constraintlayout.widget.ConstraintLayout>



</LinearLayout>

請嘗試使用此代碼(將此代碼粘貼到 xml 布局文件中)並獲得結果。 注意:您必須按照此處給出的定義約束。

我建議你使用include 請注意,如果您將android:id...包含到<include />標記中,它將覆蓋在包含的布局中定義的任何 id。 例如:

<include
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:id="@+id/some_id_if_needed"
   layout="@layout/yourlayout" />

你的布局.xml:

<LinearLayout
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:id="@+id/some_other_id">
   <Button
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:id="@+id/button1" />
 </LinearLayout>

然后,您將在代碼中引用此包含的布局,如下所示:

View includedLayout = findViewById(R.id.some_id_if_needed);
Button insideTheIncludedLayout = (Button)includedLayout.findViewById(R.id.button1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM