欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android布局——Preference自定义layout的方法

程序员文章站 2023-11-12 10:05:04
导语:preferenceactivity是一个方便设置管理的界面,但是对于界面显示来说比较单调,所以自定义布局就很有必要了。本文举例说明在preference中自定义la...
导语:preferenceactivity是一个方便设置管理的界面,但是对于界面显示来说比较单调,所以自定义布局就很有必要了。本文举例说明在preference中自定义layout的方法。笔者是为了在设置中插入@有米v4广告条才研究了一晚上的。

正文:首先preferencescreen是一个xml文件于res/xml目录下,不属于layout文件。要插入layout,有两种方法。
1.使用preference的android:@layout属性
1)xml文件中preference的添加
复制代码 代码如下:

<preference android:layout="@layout/youmi_ad" android:key="youmi_ad"/>

2)layout.xml
复制代码 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<!-- 有米广告 -->
<akai.settings.youmiad
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignparentbottom="true"
android:gravity="center_horizontal"
/>
</linearlayout>

3)由于v4版本的广告条需要自己定义layout载体,所以这里重载了一个linearlayout,自定义布局也是如此。

在youmiad.java中处理布局文件,其他布局类似,不再叙述。
复制代码 代码如下:

public class youmiad extends linearlayout{
public youmiad(context context) {
super(context);
init(context);
}
public youmiad(context context, attributeset attrs) {
super(context, attrs);
init(context);
}
private void init(context context) {
//init youmi ad
adview adview = new adview(context, adsize.size_320x50);
this.addview(adview);
adview.setadlistener(new adviewlinstener() {
@override
public void onswitchedad(adview arg0) {
log.i("youmi", "广告条切换");
}
@override
public void onreceivedad(adview arg0) {
log.i("youmi", "请求广告成功");
}
@override
public void onfailedtoreceivedad(adview arg0) {
log.i("youmi", "请求广告失败");
}
});
}

}

2.将layout添加到activity中 setcontentview(r.layout.youmi_ad)以自定义内容
1)xml文件中preference的添加
复制代码 代码如下:

<preference android:layout="@layout/youmi_ad" android:key="youmi_ad"/>

2)layout.xml,需要添加一个listview控件,且id为list,不然不能运行,应该是由于preferenceactivity是一个list的原因吧。
复制代码 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<listview
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawselectorontop="false"
android:layout_weight="1"
/>
<!-- 有米广告 -->
<linearlayout
android:id="@+id/adlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignparentbottom="true"
android:gravity="center_horizontal"
/>
</linearlayout>

3)在activity中的oncreate添加setcontentview(r.layout.youmi_ad);然后就可以使用findviewbyid去获取自定义布局下的控件了。