安卓:可复用自定义组件(类似实现一个TiTleBar)

首先 自定义一个View 此View继承于LinearLayout

public class MyView extends LinearLayout 

重写他的构造,在第二个构造中写一个初始化方法进行操作

initview(context,attrs);

为View写一个xml(写你要用的布局)
在values下创建一个attr.xml{
reference 资源
string 字符串
不一一介绍了,自己看吧,一共10种
}

<declare-styleable name="MyView">
    <attr name="myleft" format="reference"/>
    <attr name="myright" format="reference"/>
    <attr name="mycenter" format="reference"/>
</declare-styleable>

资源写好后,开始获取与判断

//初始化自定义组件
private void initview(Context context, AttributeSet attrs) {
    //加载布局
    View view = LayoutInflater.from(context).inflate(R.layout.mytitleview, null);
    //初始化控件
    textView_left=view.findViewById(R.id.mytitleview_left_text);
    textView_right=view.findViewById(R.id.mytitleview_right_text);
    textView_center=view.findViewById(R.id.mytitleview_center_text);

    //获取属性
    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
    //资源(参数:1.资源id 2.默任值)
    int left = typedArray.getResourceId(R.styleable.MyView_myleft, 0);
    int right = typedArray.getResourceId(R.styleable.MyView_myright, 0);
    int center = typedArray.getResourceId(R.styleable.MyView_mycenter, 0);
    //判断是否为空 空会取默认值 不空就设置资源
    if(left!=0){
        textView_left.setText(left);
    }
    if(right!=0){
        textView_right.setText(right);
    }
    if(center!=0){
        textView_center.setText(center);
    }
    //添加
    this.addView(view);
    //释放资源
    typedArray.recycle();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值