频道栏目
首页 > 资讯 > Android > 正文

Android布局xml的include

15-05-29        来源:[db:作者]  
收藏   我要投稿
在一个项目中我们可能会需要用到相同的布局设计,如果都写在一个xml文件中,代码显得很冗余,并且可读性也很差,所以我们可以把相同布局的代码单独写成一个模块,然后用到的时候可以通过 标签来重用layout代码。


btn.xml:
  1. android:layout_width="fill_parent"
  2. android:layout_height="wrap_content"
  3. android:orientation="vertical" >
  4. 复制代码 main.xml
    1. android:layout_width="fill_parent"
    2. android:layout_height="fill_parent"
    3. android:orientation="vertical"
    4. >
    5. android:layout_width="fill_parent"
    6. android:layout_height="wrap_content"
    7. android:text="@string/hello" />
    8. 复制代码 TestActivity:
      1. package com.hilary;
      2.  
      3. import android.app.Activity;
      4. import android.graphics.Color;
      5. import android.os.Bundle;
      6. import android.view.View;
      7. import android.view.View.OnClickListener;
      8. import android.widget.Button;
      9. import android.widget.LinearLayout;
      10. import android.widget.TextView;
      11.  
      12. import com.hialry.R;
      13. /**
      14. *
      15. *@author:hilary
      16. *@Date:2011-12-8
      17. *@description:
      18. *
      19. **/
      20. public class TestActivity extends Activity {
      21. private TextView tv = null;
      22. private LinearLayout ll = null;
      23. private LinearLayout ll2 = null;
      24.  
      25. /** Called when the activity is first created. */
      26. @Override
      27. public void onCreate(Bundle savedInstanceState) {
      28. super.onCreate(savedInstanceState);
      29. setContentView(R.layout.main);
      30. tv = (TextView) findViewById(R.id.tv);
      31. //如果一个布局文件中包含同一个xml文件,这两个xml中的控件Id是一样的,当需要操作这些控件时,需要通过定义这两个View来加以区分,
      32. //如果就包含同一个xml文件侧不需要此步操作
      33. ll = (LinearLayout) findViewById(R.id.in1);
      34. ll2 = (LinearLayout) findViewById(R.id.in2);
      35.  
      36. ll.setBackgroundColor(Color.RED);
      37.  
      38. Button btn = (Button) ll.findViewById(R.id.btn);
      39. btn.setOnClickListener(new OnClickListener() {
      40.  
      41. @Override
      42. public void onClick(View v) {
      43. tv.setText("My name is hilary");
      44. }
      45. });
      46.  
      47. Button btn2 = (Button) ll2.findViewById(R.id.btn);
      48. btn2.setOnClickListener(new OnClickListener() {
      49.  
      50. @Override
      51. public void onClick(View v) {
      52. tv.setText(" You select second Button!");
      53.  
      54. }
      55. });
      56. }
      57. } 复制代码 如果没有include标签,所有布局代码都写在一个xml文件中,界面会显得很冗余,可读性很差。而且界面加载的时候是按照顺序加载的,前面的布局不能调用其后面的布局id。而采用include后,一个include中可以引用其后的include中的布局id属性 -->
相关TAG标签
上一篇:ContentProvider实例
下一篇:Android的OutOfMemory解决
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站