Android實戰經驗之Incude便簽
當我們做項目時經常會用到相同的布局設計,如果都寫在一個xml文件中,代碼顯得很冗余,,讓人有一種去死的感覺,可讀性也很差。
所以我們可以把相同布局的代碼單獨拿出來放在一個xml文件中,通過<include /> 標簽來重用它。這樣我們的代碼顯得比較清潔,一目了然。
讀者對代碼的整體布局有一個深入的了解。
1 include標簽只有layout屬性是必須的
2.include標簽若指定了ID屬性,而你的layout也定義了ID,則你的layout的ID會被覆蓋
3 在include標簽中所有的android:layout_*都是有效的。
但前提是必須要寫layout_width和layout_height兩個屬性,否則無效 。
看一個例子:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<include
android:id="@+id/include"
layout="@layout/other" />
</LinearLayout>
include要引用的那個xml:other.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/free_bg_small_3" />
</LinearLayout>
IncludeActivity.java
package xiaosi.include; import android.app.Activity; import android.os.Bundle; public class IncludeActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!