標籤:
layout也可以include不聽說過沒呢
include就是將某個寫好的layout添加到另一個layout裡
include好處有:
- 減少在主布局檔案中的代碼量,看起來更加清晰。
- 把各部分獨立開來,方便管理。
- 可以多處複用
然後我們通常都會寫個頭部和腳部吧
在主的layout中
最好不要直接include
最好加一層Linearlayout
然後再設定他們是靠頂部還是靠底部
如
<?xml version="1.0" encoding="utf-8"?><RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true"> <include layout="@layout/header"></include> </LinearLayout> <LinearLayout android:id="@+id/frameMenu" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true"> <include layout="@layout/footer"></include> </LinearLayout></RelativeLayout>
android:layout_alignParentTop=”true”是靠頂部
android:layout_alignParentBottom=”true”是靠底部
include後控制項的id也是設定好的id,只要是相應的view引用就好了。
頭部和腳部設好了
接下來就是中間的部分
我們採用Fragmlayout
把他放在腳部和頭部中間
別忘了給這個Fragmlayout加個id
Fragment載入快,輕量級
主Activity我們採用FragmentActivity
建立完FragmentActivity後就是要建立一個繼承自Fragment的類
在這個Fragment裡的
重寫onCreateView方法
解析layout,返回view
@Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { //這裡的layout換成自己想要的layout View view=inflater.inflate(R.layout.activity_scan,null); return view; }
好,回到主activity
要讓中間的Framlayout載入我們的Fragmet也是很簡單的
FragmentTransaction fragmentTransaction = this.getSupportFragmentManager().beginTransaction();fragmentTransaction.replace(R.id.frame_content, new TestFragment());fragmentTransaction.commit();
只需三步即可完成載入
就這樣UI架構已經搞好啦。
安卓日記——利用include和Framelayout搭建app UI架構