重用布局文件 include标签
假使我们遇到这么一种情况,我们需要开发一个app,这个app的基本所有的Activity都使用到了相同的布局,我们该如何设计?我们是给这些个Activity布局文件都统一加上一样的布局代码吗?但是这样维护起来很麻烦,修改很不方便,Android布局中有没有一种类似于编程语言的include语法呢?答案是有的,但是sdk的demo并没有说出使用方法,但这并不说明不好使用,其实很简单。下面的IncludeXmlTest工程给出了样式。
我们新建一个IncludeXmlTest工程,我们先从布局文件上下手,我们新建一个真正的real.xml文件,来实现我们的布局,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>然后在我们需要引入的xml文件中,include这个real.xml就可以了,我这个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/real"/>
</LinearLayout>这个include部分就是引入了real.xml的布局,之后我们在程序中只需要布局main.xml文件即可:
public class IncludeXmlTestActivity extends Activity {
private TextView mTextView;
private Button mButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
}
/**
* 设置view
* */
public void initView(){
mTextView = (TextView) findViewById(R.id.text);
mButton = (Button)findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mTextView.setText("hello, i am here");
}
});
}
}http://www.ourunix.org/android/post/87.html
相关推荐
89243453 2020-08-24
Erick 2020-08-21
earthhouge 2020-07-19
klarclm 2020-06-14
拉斯厄尔高福 2020-06-02
Jaystrong 2020-06-02
hongsheyoumo 2020-06-02
twater000 2020-05-30
adonislu 2020-05-17
Haopython 2020-05-09
浅梦墨汐 2020-05-12
shenwenjie 2020-05-09
fengjing81 2020-05-08
lihuifei 2020-05-04
wbczyh 2020-05-03
LychieFan 2020-04-30
luckymaoyy 2020-04-25
Cypress 2020-04-25