安卓日記——利用include和Framelayout搭建app UI架構

來源:互聯網
上載者:User

標籤:

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架構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.