更新時間:2021-12-29
通過include可以重復使用某個布局,相同的頁面不需要重復的去寫了,復用,
1. 使用方式示例
1)創建一個layout,如:my_include_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/black">
<TextView
android:id="@+id/src_include_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="this is include"
android:textColor="@color/white"
android:textSize="30sp"
/>
</LinearLayout>

2)通過include重復使用上方的布局
在 activity_main.xml中通過include重復使用布局
<?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">
<include
android:id="@+id/my_include_1"
layout="@layout/my_include_layout" />
<include
android:id="@+id/my_include_2"
layout="@layout/my_include_layout"
/>
</LinearLayout>

3)通過activity操作
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// id為include處設定的
View include_1 = findViewById(R.id.my_include_1);
View include_2 = findViewById(R.id.my_include_2);
// 通過view去查找子控制元件
TextView include_1_tv = include_1.findViewById(R.id.src_include_tv);
TextView include_2_tv = include_2.findViewById(R.id.src_include_tv);
// 給子控制元件TextView設定text
include_1_tv.setText("new include1 text value");
include_2_tv.setText("new include2 text value");
}
}
4)效果

5)注意
當在include中添加如下代碼,即增加 layout_margin 沒有效果的
<include
android:id="@+id/my_include_2"
layout="@layout/my_include_layout"
android:layout_margin="10dp"
/>
如果要使用 標記來替換布局屬性,您必須同時替換 android:layout_height 和 android:layout_width 才能讓其他布局屬性生效,

地址: https://developer.android.google.cn/training/improving-layouts/reusing-layouts
改為如下代碼:
<include
android:id="@+id/my_include_2"
layout="@layout/my_include_layout"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="10dp"
/>
效果如下:

2. 參考檔案:
Re-using layouts with :https://developer.android.google.cn/training/improving-layouts/reusing-layouts
好記性不如爛筆頭!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/398029.html
標籤:AI
上一篇:Android merge
