位置: 编程技术 - 正文

Android include 标签注意点

编辑:rootadmin

推荐整理分享Android include 标签注意点,希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:,内容如对您有帮助,希望把文章链接给更多的朋友!

Android include 标签注意点

转自: 但是也有一些需要注意的地方,下面是本人在项目中碰到过的一个问题,做此记录,便于以后查看。 include标签用法。 1.新建一个xml文件,命名 head.xml head.xml文件内容如下: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=" android:id="@&#;id/index_linear_foot" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <ImageView android:id="@&#;id/head_btn_refresh" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> 2.新建一个布局文件,命名 main.xml main.xml文件内容如下: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <include android:layout_width="fill_parent" android:layout_height="wrap_content" layout="@layout/head" /> </LinearLayout> 注意:上面我们的include标签中是没有为它指定id的。 3.新建一个MainActivity,设置布局文件为main.xml; 4.假设我现在需要在代码中为head.xml中的RelativeLayout容器设置背景图片。 代码如下: //获得布局容器对象 RelativeLayout head = (RelativeLayout)findViewById(R.id.index_linear_foot); //设置背景图片 head.setBackgroundResource(R.drawable.head); 这样就OK了。 5.刚刚说到,我们的include标签中是没有为它指定id的,假设我们现在的main.xml文件布局容器是RelativeLayout,而我需要把某个控件放在head.xml下面。就需要使用到RelativeLayout布局容器的特有属性 android:layout_below="" 属性。还需要为include指定id属性。 那我们的main.xml文件变成如下: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" > <include android:id="@&#;id/main_head" android:layout_width="fill_parent" android:layout_height="wrap_content" layout="@layout/head" /> <ListView android:id="@&#;id/listview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@&#;id/main_headb" /> </RelativeLayout> 那接下来我们在运行我们的实例,结果发现,代码在运行到head.setBackgroundResource(R.drawable.head); 这一句的时候抛异常了 java.lang.NullPointerException 原来:如果include指定了id的话,就不能直接把它里面的控件当成主xml中的控件来直接获得了,必须先获得这个xml布局文件,再通过布局文件findViewById来获得其子控件。 代码如下 View layout = getLayoutInflater().inflate(R.layout.head, null); RelativeLayout head= (RelativeLayout)layout.findViewById(R.id.index_linear_foot); //设置背景图片 head.setBackgroundResource(R.drawable.head); 这样就可以了。

新的开始 接触Android有一段时间了,一直都是要什么学什么没有系统的学习过.很多时候有了idea,但是不知道要用什么方式来实现,因此今天开始系统的学习Android.这里

idea 的代码分析 代码分析IntelliJIDEA通过对代码的检查来进行代码分析。对Java和其他支持的语言有无数的代码检测行为存在。该检查不仅能发现编译错误,还能发现效率

Android学习 - Android应用如何支持屏幕多尺寸多分辨率问题 作为Android应用程序开发者都知道android是一个碎片化的世界。多种系统版本、多种尺寸、多种分辨率、多种机型,还有不同的厂商定制的不同ROM,你开发

本文链接地址:https://www.jiuchutong.com/biancheng/381101.html 转载请保留说明!

上一篇:Android Camera 实时滤镜(八)(android camera1)

下一篇:新的开始(新的开始励志句子)

免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

鄂ICP备2023003026号

网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

友情链接: 武汉网站建设 电脑维修 湖南楚通运网络