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

Android 自定义组合布局

2016-06-22 11:03 363 查看
package com.itheima.mobilesafe66.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itheima.mobilesafe66.R;

/**
* 自定义组合控件
*
* 1. 写一个类继承RelativeLayout(ViewGroup) 2. 写布局文件 3.
* 将布局添加到RelativeLayout中(initView方法) 4. 增加api 5. 自定义属性(1. values/attrs.xml, 2.
* 声明命名空间 , 3.在自定义view中配置属性, 4. 在自定义view中加载属性值 )
*
* @author Kevin
*
*/
public class SettingItemClickView extends RelativeLayout {

private TextView tvTitle;
private TextView tvDesc;

public SettingItemClickView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
initView();
}

public SettingItemClickView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}

public SettingItemClickView(Context context) {
super(context);
initView();
}

/**
* 初始化布局
*/
private void initView() {
View child = View.inflate(getContext(),
R.layout.setting_item_click_view, null);// 初始化组合控件布局

tvTitle = (TextView) child.findViewById(R.id.tv_title);
tvDesc = (TextView) child.findViewById(R.id.tv_desc);

this.addView(child);// 将布局添加给当前的RelativeLayout对象
}

/**
* 设置标题
*
* @param title
*/
public void setTitle(String title) {
tvTitle.setText(title);
}

/**
* 设置表述
*
* @param desc
*/
public void setDesc(String desc) {
tvDesc.setText(desc);
}
}


1、对自定义控件进行代码填充

sicLocation = (SettingItemClickView) findViewById(R.id.sic_location);

sicLocation.setTitle(“归属地提示框位置”);

sicLocation.setDesc(“设置归属地提示框的显示位置”);

2、在values的attrs中设置组合布局属性

(1)定义

<?xml version="1.0" encoding="utf-8"?>
<resources>

<declare-styleable name="SettingItemView">
<attr name="title" format="string" />
<attr name="desc_on" format="string" />
<attr name="desc_off" format="string" />
</declare-styleable>

</resources>


(2)引用 activity_setting.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:itheima="http://schemas.android.com/apk/res/com.itheima.mobilesafe66"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textView1"
style="@style/TitleStyle"
android:text="设置中心" />

<com.itheima.mobilesafe66.view.SettingItemView
android:id="@+id/siv_update"
android:layout_width="match_parent"
android:layout_height="wrap_content"
itheima:desc_off="自动更新已关闭"
itheima:desc_on="自动更新已开启"
itheima:title="自动更新设置" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  布局