自定义控件

1.先自定义一个继承viewGroup的类,并重写带两个参数的构造函数

public class TitleLayout extends LinearLayout {
    public TitleLayout(final Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.title,this);//LayoutInflater的from方法可以构建一个LayoutInflater对象,然后调用inflate方法可以动态加载布局,第一个参数是布局文件,第二个参数代表添加一个父布局,这里指定为TitleLayout
        Button back=findViewById(R.id.back);
        TextView title=findViewById(R.id.title);
        Button edit=findViewById(R.id.edit);
        TypedArray attr=context.obtainStyledAttributes(attrs,R.styleable.TitleLayout);
        //自定义的属性赋值给title
        if (attr!=null){
            String titleName=attr.getString(R.styleable.TitleLayout_titleName);
            if (!TextUtils.isEmpty(titleName)){
                title.setText(titleName);
            }
            attr.recycle();
        }
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ((Activity)context).finish();
            }
        });
        edit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context,"您点击了编辑按钮",Toast.LENGTH_SHORT).show();
            }
        });

    }
}

2.自定义控件的自定义的属性,在attrs.xml文件中定义



    
        
    

3.自定义控件的调用,在需要自定义控件的布局文件中写入以下代码即可。


你可能感兴趣的:(自定义控件)