自定义控件里面没有属性,没有文字,没有图片,所以会再写一个布局(有Textview,Imageview),用自定义控件的属性去设置你的那个布局里面的属性值;
1.新建一个自定义控件的类(ContentTitle),继承自LinearLayout(布局),实现方法;
2.初始化布局控件(R.layout.contentTitle),写一个TextView,ImageView;
3.在values中新建一个attrs.xml自定义其属性值;
4.在主xml中写自定义控件,设置其属性;
5.在类里面得到布局,以及控件,属性,设置其属性;
6.展示;
//第一步:
public class ContentTitle extends LinearLayout {
private LinearLayout rootView;
private TextView name;
private ImageView image;
public ContentTitle(Context context) {
this(context, null);
}
public ContentTitle(Context context, AttributeSet attrs) {
this(context, attrs, -1);
}
public ContentTitle(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//初始化控件
initView(context);
initAttrs(context, attrs);
}
//第二步:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<ImageView
android:id="@+id/image"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自定义属性"/>
</LinearLayout>
//第三步:values--->attrs.xml
<resources>
<declare-styleable name="ContentTitle">
<attr name="left_image" format="reference"></attr>
<attr name="content_text" format="string"></attr>
<attr name="content_text_color" format="color"></attr>
<attr name="content_text_size" format="dimension"></attr>
</declare-styleable>
</resources>
//第四步:
<com.bw.a123.high5_day.ContentTitle
android:id="@+id/contentTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
customer:content_text="1111111111111"
customer:content_text_color="#ae2c2c"
customer:content_text_size="20dp"
customer:left_image="@mipmap/q9">
</com.bw.a123.high5_day.ContentTitle>
//第五步:
//===========================初始化控件====================================================
private void initView(Context context) {
rootView = (LinearLayout) View.inflate(context, R.layout.item, this);
name = rootView.findViewById(R.id.name);
image = rootView.findViewById(R.id.image);
}
//===========================初始化属性====================================================
private void initAttrs(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ContentTitle);
//设置图片
Drawable drawable = typedArray.getDrawable(R.styleable.ContentTitle_left_image);
//判断是否为空
if (drawable != null) {
image.setImageDrawable(drawable);
}
//设置文字
CharSequence text = typedArray.getText(R.styleable.ContentTitle_content_text);
if (!TextUtils.isEmpty(text)) {
name.setText(text);
}
//设置颜色
int color = typedArray.getColor(R.styleable.ContentTitle_content_text_color, -1);
if (color != -1) {
name.setTextColor(color);
}
//设置大小
float dimension = typedArray.getDimension(R.styleable.ContentTitle_content_text_size, 0f);
name.setTextSize(dimension);