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

Android布局优化之include

2016-04-25 09:28 363 查看
在我们布局的过程中经常会碰到很多画面非常类似,仅仅是文字什么的不同,象一些导航啊,菜单啊之类的。如果有过html经验的同学都知道有include可以导入公告部分,这样能大大的减少代码的重复,提高复用率。那么在Android中是否也能这样呢?
答案是肯定的。

现在我们直接看代码。

首先看看目录结构



在目录结构里我们可以看到除了main_activity.java文件和activity_main.xml布局文件之外,还有一个commen.xml文件。这个文件就是一个公共导航,我们来看一下布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#000000"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_height="wrap_content">

<TextView
android:id="@+id/back"
android:text="返回"
android:textColor="#ffffff"
android:textSize="15sp"
android:layout_marginLeft="10dp"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<TextView
android:id="@+id/title"
android:text="标题"
android:textColor="#ffffff"
android:textSize="17sp"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<TextView
android:id="@+id/fun"
android:text="功能"
android:textColor="#ffffff"
android:textSize="15sp"
android:layout_marginRight="10dp"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>


布局文件写完之后我们看看activity_main.xml这个布局文件中怎么引入这个commen.xml的:

<span style="color:#3f3f3f;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

</span><span style="color:#ff0000;"> <include layout="@layout/commen"></include></span><span style="color:#3f3f3f;">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
</span>


注意标红的那一行代码,直接include标签 加一个layout属性,就把commen这个公共文件导入了。同时我们在这个导入的下面还加了个TextView,现在我们来看看运行的效果:



就这样就实现了include的导入,那么有一个问题,我们在activity_main.xml这个布局文件中导入了commen.xml这个公共的头文件,那在MainActivity中是否能直接用commen里面的控件呢? 这里我们做了个尝试:

package com.example.lolli.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity{
// 定义include进来的textView
private TextView backText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化TextView
backText = (TextView) findViewById(R.id.back);

//  设置TextView的点击事件
backText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "你点击了返回按钮", Toast.LENGTH_SHORT).show();
}
});
}
}


我对头部的返回的TextView做了初始化工作,并设置了点击事件,我们看看运行的效果:



点击按钮生效了。其实include是把整个页面都弄进当前布局文件了,就是当前布局文件的一分子,我们能直接使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: