自定义View笔记

来源:互联网 发布:河北seo按效果付费 编辑:程序博客网 时间:2024/06/05 17:27

这里参考了洪洋大神博客中的许多内容,主要是用于学习自定义View的一个阶段性的总结。

使用自定义View的时候主要有以下的步骤:

1.定义这个View中需要使用到的属性。

2.在View中的构造方法中获得我们的属性

3.重写OnMesure方法

4.重写OnDraw方法

首先我们定义一个属性文件存放在在res/values/attr.xml这个路径下面。

<?xml version="1.0" encoding="utf-8"?><resources>    <attr name="mtitleText" format="string" />    <attr name="mtitleTextSize" format="dimension" />    <attr name="mtitleTextColor" format="color" />    <attr name="mimage" format="reference" />    <attr name="mimageScaleType">        <enum name="fillXY" value="0" />        <enum name="center" value="1" />    </attr>    <declare-styleable name="CustomImageView">        <attr name="mtitleText" />        <attr name="mtitleTextSize" />        <attr name="mtitleTextColor" />        <attr name="mimage" />        <attr name="mimageScaleType" />    </declare-styleable></resources>
然后我们来看一下Layout文件中是如何使用这些文件的:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:aaa="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.lsj.viewgrouptest.MainActivity">        <ScrollView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/scrollView"            android:layout_gravity="center_horizontal"            android:fillViewport="false">                <LinearLayout                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:orientation="vertical">                        <com.example.lsj.viewgrouptest.CustomImageView                            android:layout_width="500dp"                            android:layout_height="500dp"                            android:layout_margin="10dp"                            android:padding="10dp"                            aaa:mimage="@drawable/a"                            aaa:mimageScaleType="center"                            aaa:mtitleText="555"                            aaa:mtitleTextColor="#ff0000"                            aaa:mtitleTextSize="30sp"                            />                        <com.example.lsj.viewgrouptest.CustomImageView                            android:layout_width="500dp"                            android:layout_height="500dp"                            android:layout_margin="10dp"                            android:padding="10dp"                            aaa:mimage="@drawable/a"                            aaa:mimageScaleType="center"                            aaa:mtitleText="555"                            aaa:mtitleTextColor="#00ff00"                            aaa:mtitleTextSize="20sp"                            />                        <com.example.lsj.viewgrouptest.CustomImageView                            android:layout_width="500dp"                            android:layout_height="500dp"                            android:layout_margin="10dp"                            android:padding="10dp"                            aaa:mimage="@drawable/b"                            aaa:mimageScaleType="center"                            aaa:mtitleText="555"                            aaa:mtitleTextColor="#00ff00"                            aaa:mtitleTextSize="12sp"                            />                </LinearLayout>        </ScrollView></LinearLayout>

因为图片比较大,所以使用一个ScrollView包一下,使用ScrollView的时候需要注意的是:下面的其他View需要通过一个LinearLayout/RealtiveLayout包裹一下,因为ScrollView中默认只能包含一个View。

使用自定义View的时候,尖括号中写上我们项目的包名即可。

下面我们再来看一下这个CustomImageView类的具体实现:

public class CustomImageView extends View{private int mWidth;private int mHeight;private Bitmap mImage;private int mImageScale;private static final int IMAGE_SCALE_FITXY = 0;private static final int IMAGE_SCALE_CENTER = 1;private String mTitle;//标题private int mTextColor;//字体颜色private int mTextSize;//字体大小private Paint mPaint;//画笔private Rect mTextBound;private Rect rect;public CustomImageView(Context context, AttributeSet attrs){this(context, attrs, 0);}public CustomImageView(Context context){this(context, null);}public CustomImageView(Context context, AttributeSet attrs, int defStyle){super(context, attrs, defStyle);TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomImageView, defStyle, 0);//获得所有的属性int n = a.getIndexCount();//获得属性的个数for (int i = 0; i < n; i++){int attr = a.getIndex(i);switch (attr){case R.styleable.CustomImageView_mimage:mImage = BitmapFactory.decodeResource(getResources(), a.getResourceId(attr, 0));break;case R.styleable.CustomImageView_mimageScaleType:mImageScale = a.getInt(attr, 0);break;case R.styleable.CustomImageView_mtitleText:mTitle = a.getString(attr);break;case R.styleable.CustomImageView_mtitleTextColor:mTextColor = a.getColor(attr, Color.BLACK);break;case R.styleable.CustomImageView_mtitleTextSize:mTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,16, getResources().getDisplayMetrics()));break;}}a.recycle();//将TapedArray进行回收rect = new Rect();mPaint = new Paint();mTextBound = new Rect();mPaint.setTextSize(mTextSize);mPaint.getTextBounds(mTitle, 0, mTitle.length(), mTextBound);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){/** */int specMode = MeasureSpec.getMode(widthMeasureSpec);int specSize = MeasureSpec.getSize(widthMeasureSpec);if (specMode == MeasureSpec.EXACTLY)// match_parent , accurate{Log.e("xxx", "EXACTLY");mWidth = specSize;} else{int desireByImg = getPaddingLeft() + getPaddingRight() + mImage.getWidth();//int desireByTitle = getPaddingLeft() + getPaddingRight() + mTextBound.width();if (specMode == MeasureSpec.AT_MOST)// wrap_content{int desire = Math.max(desireByImg, desireByTitle);mWidth = Math.min(desire, specSize);Log.e("xxx", "AT_MOST");}}/*** * */specMode = MeasureSpec.getMode(heightMeasureSpec);specSize = MeasureSpec.getSize(heightMeasureSpec);if (specMode == MeasureSpec.EXACTLY)// match_parent , accurate{mHeight = specSize;}else{int desire = getPaddingTop() + getPaddingBottom() + mImage.getHeight() + mTextBound.height();if (specMode == MeasureSpec.AT_MOST)// wrap_content{mHeight = Math.min(desire, specSize);}}setMeasuredDimension(mWidth, mHeight);}@Overrideprotected void onDraw(Canvas canvas){/** */mPaint.setStrokeWidth(4);mPaint.setColor(Color.CYAN);canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);rect.left = getPaddingLeft();rect.right = mWidth - getPaddingRight();rect.top = getPaddingTop();rect.bottom = mHeight - getPaddingBottom();mPaint.setColor(mTextColor);mPaint.setStyle(Style.FILL);/** */if (mTextBound.width() > mWidth){TextPaint paint = new TextPaint(mPaint);String msg = TextUtils.ellipsize(mTitle, paint, (float) mWidth - getPaddingLeft() - getPaddingRight(),TextUtils.TruncateAt.END).toString();canvas.drawText(msg, getPaddingLeft(), mHeight - getPaddingBottom(), mPaint);} else{//canvas.drawText(mTitle, mWidth / 2 - mTextBound.width() * 1.0f / 2, mHeight - getPaddingBottom(), mPaint);}//rect.bottom -= mTextBound.height();if (mImageScale == IMAGE_SCALE_FITXY){canvas.drawBitmap(mImage, null, rect, mPaint);}else{//rect.left = mWidth / 2 - mImage.getWidth() / 2;rect.right = mWidth / 2 + mImage.getWidth() / 2;rect.top = (mHeight - mTextBound.height()) / 2 - mImage.getHeight() / 2;rect.bottom = (mHeight - mTextBound.height()) / 2 + mImage.getHeight() / 2;canvas.drawBitmap(mImage, null, rect, mPaint);}}}这里 TypedArray使用完毕后要注意回收,不然会造成内存溢出的错误,

下面就贴出一个效果图把(:尴尬


0 0
原创粉丝点击