Android开发之自定义控件的基本介绍(附源码)
生活随笔
收集整理的這篇文章主要介紹了
Android开发之自定义控件的基本介绍(附源码)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
老套路先看效果圖:
一個特別簡單的字母排序列表如上圖:
先看下有哪些屬性:
<com.xiayiye.honorfirst.custom.CustomNumViewandroid:id="@+id/cn_view"android:layout_width="40dp"android:layout_height="match_parent"android:layout_alignParentRight="true"android:background="@android:color/holo_blue_bright"app:num_text_center="false"app:num_text_color="@android:color/white"app:num_text_left="true"app:num_text_right="true"app:num_text_size="20sp" />非常簡單,就加了五個自定義屬性分別是:文字字母居中,居左,居右,文字字母大小,顏色等。如何自定義的呢?
1.我們需要在value文件夾下面新建一個attrs文件,然后定義一些屬性如下:
<?xml version="1.0" encoding="utf-8"?> <resources><declare-styleable name="CustomNumView"><attr name="num_text_color" format="reference|color" /><attr name="num_text_size" format="dimension" /><attr name="num_text_left" format="boolean" /><attr name="num_text_right" format="boolean" /><attr name="num_text_center" format="boolean" /></declare-styleable> </resources>然后寫個類繼承view。實現相關的三四個構造方法。字母是通過onDraw方法畫上去的,具體計算步驟就不講解了
然后通過TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomNumView);拿到自定義的xml文件里面的自己定義的相關屬性
textColor = typedArray.getColor(R.styleable.CustomNumView_num_text_color, Color.WHITE);float dimension = typedArray.getDimension(R.styleable.CustomNumView_num_text_size, 10);isLeft = typedArray.getBoolean(R.styleable.CustomNumView_num_text_left, false);isCenter = typedArray.getBoolean(R.styleable.CustomNumView_num_text_center, false);isRight = typedArray.getBoolean(R.styleable.CustomNumView_num_text_right, false);typedArray.recycle();上面就是拿到的自定義屬性的五個屬性方法
然后根據拿到的方法進行相應的邏輯判斷處理后在xml布局中就可以使用了
?
@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);for (int i = 0; i < data.length; i++) {String str = data[i];float textWidth = paint.measureText(str);float textHeight = bounds.height(); // float x = geZiWidth * 0.5f - textWidth * 0.5f;float y = (geZiHeight * 0.5f + textHeight * 0.5f) + i * geZiHeight;float x = 0;if (isCenter) {//xml中定義了居中就居中顯示x = geZiWidth * 0.5f - textWidth * 0.5f;} else if (isLeft) {//xml中定義了左邊就左邊顯示x = 0;} else if (isRight) {//xml中定義了右邊就右邊顯示x = geZiWidth - textWidth;} else {//默認居中x = geZiWidth * 0.5f - textWidth * 0.5f;}paint.getTextBounds(str, 0, str.length(), bounds);paint.setColor(selectNum == i ? Color.RED : textColor);canvas.drawText(str, x, y, paint);// canvas.drawText(str, geZiWidth * 0.5f - paint.measureText(str) * 0.5f, getHeight()/26*(i+1), paint);}}咱們來看下最終的效果圖:
?
源碼已上傳GitHub:點擊瀏覽
字母列表view源碼頁面:點擊瀏覽
總結
以上是生活随笔為你收集整理的Android开发之自定义控件的基本介绍(附源码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 三星推出新款防水便携式扬声器 Sound
- 下一篇: 《英雄联盟手游》体验服 4.1 版本更新