1. 控件的Layout文件:
@layout_item.xml
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
...
</LinearLayout>
</merge>
2. 自定义控件的自定义属性:
@attrs.xml
<declare-styleable name="Item">
<attr name="title" format="string" />
<attr name="showTitle" format="boolean" />
</declare-styleable>
3. 控件类
@Item.java
public class Item extends LinearLayout {
private TextView mTitleView;
private boolean showText;
public Item(Context context) {
this(context, null);
}
public Item(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.layout_item, this, true);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.xxxItem);
String title = array.getString(R.styleable.xxxItem_title);
showText = array.getBoolean(R.styleable.xxxItem_showText, true);
array.recycle();// 用完要回收
setTitle(title);
//动态添加控件
if (xxx) {
mRemarks = new TextView(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 0);
params.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;// layout_gravity属性
mRemarks.setGravity(Gravity.CENTER);// gravity属性
mRemarks.setLayoutParams(params);
mRemarks.setTextColor(context.getColor(R.color.xxx));
setRemarks(remarks);
view.addView(mRemarks, new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 0));
}
}
}
4. 控件的使用
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<com.xxx.xxx.xxx.Item
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:title="xxx" />
</LinearLayout>
网友评论