通常重用布局文件
简单布局文件:
步骤:
1将要重用的布局 写在布局文件中,
2重用时只需要找到
<include layout="@layout/tool_bar"/>
这种情况适合简单的布局重用,。,每个重用的组件代码修改量比较小的情况,例如ToolBar,
复杂布局文件:
步骤
1.设置需要复用组件的布局
R.layout.setcenter_item
2.自定义组合控件,将布局转成view 加到自定义组合控件上。
public class SettingView extends LinearLayout {}
LayoutInflater inflater= LayoutInflater.from(getContext());
view= inflater.inflate(R.layout.setcenter_item,null);
addView(view);
3。设置自定义属性。给要添加自定义组合控件的布局添加命名空间
xmlns:myxmlns=""http://schemas.android.com/apk/res/<你的应用程序的包名>"
eg:
放在最上面!
xmlns:settingview="http://schemas.android.com/apk/com.example.xxx.mobilesoder"
并将属性名,和属性类型值填入到res/values/arrts.xml文件下
velues 下arrts.xml文件,添加属性文件。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="context" format="string"/>
<attr name="name" format="string"/>
<declare-styleable name="Popview"> //自定义控件的名字
<attr name="src" format="reference"/> //引用类型的值 例如ID
<attr name="popitemname" format="string"/>
</declare-styleable>
</resources>
布局如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:settingview="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.cuizehui.Actitys.SetActivity">
<include layout="@layout/tool_bar"/>
<com.cuizehui.Myview.SettingView
android:id="@+id/setting_black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
settingview:image="@drawable/gv_refuse"
settingview:name="黑名单服务"
settingview:context="已开启">
</com.cuizehui.Myview.SettingView>
<com.cuizehui.Myview.SettingView
android:id="@+id/setting_rock"
settingview:name="桌面优化服务"
settingview:context="已开启"
settingview:image="@drawable/monkeythree"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</com.cuizehui.Myview.SettingView>
<com.cuizehui.Myview.SettingView
android:id="@+id/setting_lostfound"
settingview:name="防丢失服务"
settingview:context="已开启"
settingview:image="@drawable/gv_fangdao"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</com.cuizehui.Myview.SettingView>
</LinearLayout>
4.使属性生效:使用构造函数中的第二个参数arrt
普通属性:
String name= attrs.getAttributeValue("http://schemas.android.com/apk/com.example.cuizehui.mobilesoder","name");
checkname.setText(name);
自定控件属性:
TypedArray ta= context.obtainStyledAttributes(attrs,R.styleable.Popview);//通过这种方式获取属性的值。不用命名空间了!
String name= ta.getString(R.styleable.Popview_popitemname);
if(name==null){
name="";
}
Drawable d = ta.getDrawable(R.styleable.Popview_src);
if (d != null) {
drawable=d;
} else {
throw new RuntimeException("图像资源为空");
}
tabTextSize = a.getDimensionPixelSize(0, tabTextSize);
其他属性获取
获取布局内控件进行设置
5自定义组合控件点击事件的处理,由于每一个组合控件的点击事件并不同这时候我们选择将监听器写在外部并传进去。
public void itemOnlickLisner(OnClickListener listener){
view.setOnClickListener(listener);
}
这样监听处理的具体时间就由调用者完成实现了。