Android笔记--简单的自定义View之组合模式

组合模式的意思就是,将几个系统原生的控件组合到一起变成新的控件。

比如说实现一个标题栏的组合控件,标题栏上会有个返回按钮和标题。

第一步:新建atts.xml文件,自定义属性,不引用系统的属性。

<resources>
    <!--告诉系统这是自定义的属性  format 所引用资源的类型 -->
    <declare-styleable name="CustomToolbar">
        <attr name="Titles" format="string"></attr>
        <attr name="TitleTextColors" format="color"></attr>
<attr name="TitleTextSize" format="dimension"></attr>
        <attr name="LeftText" format="string"></attr>
<attr name="LeftTextColor" format="color"></attr>  
	<attr name="LeftBackground" format="reference|color"></attr>    
     </declare-styleable></resources>

第二步:新建一个CustomToolbar类,继承RelativeLayout布局,因为需要获取自定义属性,所以构造器加一个AttributeSet属性。

public class CustomToolbar extends RelativeLayout {
	public CustomToolbar(Context context, AttributeSet attrs) {
    		super(context, attrs);
}

}

第三步:在构造器中使用安卓系统自带的API的TypedArray类取出atts.xml中的自定义属性使用(通过映射)。

TypedArray typedArray= context.obtainStyledAttributes(attrs, R.styleable.CustomToolbar);
TitleStr = typedArray.getString(R.styleable.CustomToolbar_Titles);
TitleTextColorInt = typedArray.getColor(R.styleable.CustomToolbar_TitleTextColors, 0);
TitleTextSizeFloat = typedArray.getDimension(R.styleable.CustomToolbar_TitleTextSize, 0);
typedArray.recycle();

第四步:在构造器中创建所需用到的控件,将自定义的属性值赋予控件,并把控件以设置好的形式加入到ViewGroup中。

TextView txt_Title=new TextView(context);

txt_Title.setTextColor(TitleTextColorInt);
txt_Title.setTextSize(TitleTextSizeFloat);
txt_Title.setText(TitleStr);
LayoutParams TitleParams=new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
TitleParams.addRule(RelativeLayout.CENTER_IN_PARENT,TRUE);addView(txt_Title,TitleParams);

第五步:将自定义的CustomToolbar类加入布局main.xml 文件中,并且使用自定义属性。

xmlns:app="http://schemas.android.com/apk/res-auto"

<com.view.CustomToolbar
    android:id="@+id/topbarid"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    app:leftBackground="#0ff"
    app:leftText="左边"
    app:leftTextColor="#000"
</com.view.CustomToolbar>

这样子,界面就完成了,接下来就是按钮的点击监听了,又要讲一遍接口回调机制了。

接口回调机制第一步:创建接口

接口回调机制第二步:暴露方法给调用者(调用者会传一个接口类型的参数,即调用者会传递一个匿名内部类,调用者把它的实现写在了匿名内部类的方法里)

接口回调机制第三步:声明一个接口变量,将映射调用者传来的接口。

接口回调机制第四步:当自定义的CustomToolbar类里的按钮被点击时,按钮的OnClick将实现传过来的接口(匿名内部类)里的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值