自定义view的第三篇,模仿的是微博运动界面的个人出生日期设置view,先看看我的效果图:
支持设置初始年份,左右滑动选择出生年份,对应的TextView的值也会改变。这个动画效果弄了好久,感觉还是比较生硬,与微博那个还是有点区别。大家有改进的方案,欢迎一起交流。
自定义View四部曲,这里依旧是这个套路,看看怎么实现的。
1.自定义view的属性:在res/values/ 下建立一个attrs.xml , 在里面定义我们的属性以及声明我们的整个样式。
//自定义属性名,定义公共属性
依次定义了字体大小,字体颜色,线的颜色3个属性,format是值该属性的取值类型。
然后就是在布局文件中申明我们的自定义view:
android:id="@+id/year_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:text="出生年份 (年)"
android:textSize="20dp" />
android:id="@+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="70dp"
myscroll:lineColor="@color/font_text"
myscroll:titleColor="@color/strong"
myscroll:titleSize="30dp">
自定义view的属性我们可以自己进行设置,记得最后要引入我们的命名空间,
xmlns:app=”http://schemas.Android.com/apk/res-auto”
2.获取自定义view的属性:
public MyScrollView(Context context) {
this(context, null);
}
public MyScrollView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyScrollView(final Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//获取我们自定义的样式属性
TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyScrollView, defStyleAttr, 0);
int n = array.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = array.getIndex(i);
switch (attr) {
case R.styleable.MyScrollView_lineColor:
// 默认颜色设置为黑色
lineColor =