首先 自定义一个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();
}