您的位置:首页 > 移动开发

安卓日记——利用include和Framelayout搭建app UI框架

2016-05-07 21:44 295 查看
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框架已经搞好啦。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android