<?xml version="1.0" encoding="utf-8" ?>
<resources>
<declare-styleable name="TextFlipperView">
<attr name="fontColor" format="color"/>
<attr name="fontSize" format="dimension"/>
</declare-styleable>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:xmg="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.wtz.textviewflipper.TextFlipperView
android:id="@+id/viewFlipper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmg:fontColor="#0f0"
xmg:fontSize="25sp"></com.example.wtz.textviewflipper.TextFlipperView>
</android.support.constraint.ConstraintLayout>
package com.example.wtz.textviewflipper;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
import android.widget.ViewFlipper;
import java.util.ArrayList;
public class TextFlipperView extends ViewFlipper {
private int mFontColor;
private float mFontSize;
public TextFlipperView(Context context) {
super(context);
}
public TextFlipperView(Context context, AttributeSet attrs) {
super(context, attrs);
int attributeCount = attrs.getAttributeCount();
for (int i = 0; i < attributeCount; i++) {
String attributeName = attrs.getAttributeName(i);
String attributeValue = attrs.getAttributeValue(i);
Log.d(getClass().getSimpleName(), "TextFlipperView: attributeName: " + attributeName
+" attributeValue: "+attributeValue);
}
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TextFlipperView);
mFontColor = typedArray.getColor(R.styleable.TextFlipperView_fontColor, Color.RED);
mFontSize = typedArray.getDimension(R.styleable.TextFlipperView_fontSize, 20);
//释放它,节约资源
typedArray.recycle();
}
//供添加数据
public void setViews(ArrayList<TextView> views){
for (int i = 0; i < views.size(); i++) {
TextView o = views.get(i);
//使用刚才获得的自定义属性fontColor fontSize
o.setTextSize(mFontSize);
o.setTextColor(mFontColor);
addView(o);
}
}
}

