- 布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_marginBottom="15dp"
android:orientation="horizontal"
xmlns:android="http://schemas.android.com/apk/res/android">
<View
android:layout_width="5dp"
android:layout_height="15dp"
android:layout_marginRight="5dp"
android:background="@color/colorPrimary"/>
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="订单信息"/>
</LinearLayout>
自定义属性
在 value 文件夹下新建 attrs.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CardTitleView">
<attr name="title_text" format="string" />
</declare-styleable>
</resources>
自定义 View
主要是加载布局,根据自定义的属性初始化控件,相关接口
public class CardTitleView extends LinearLayout {
private TextView titleText;
private String title="";
public CardTitleView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.view_cardtitle, this);
TypedArray mTypedArray=context.obtainStyledAttributes(attrs,R.styleable.CardTitleView);
titleText = (TextView) findViewById(R.id.tv_title);
title=mTypedArray.getString(R.styleable.CardTitleView_title_text);
titleText.setText(title);
//获取资源后要及时回收
mTypedArray.recycle();
}
public void setTitle(String s){
titleText.setText(s);
}
public String getTitle(){
return titleText.getText().toString();
}
}
- 调用
自定义属性的命名空间
xmlns:app="http://schemas.android.com/apk/res-auto"
<com.idjmao.sandwaybill.view.CardTitleView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:title_text="属性信息"/>