【學(xué)習(xí)筆記】自定義控件的幾種寫法

Android開發(fā)中給我們提供了豐富的控件支持,可是產(chǎn)品是不斷地發(fā)展更新的笼平,產(chǎn)品經(jīng)理的想法有時(shí)候也是比較BUG的园骆。當(dāng)軟件對(duì)UI設(shè)計(jì)的要求比較高的時(shí)候,經(jīng)常會(huì)遇到安卓自帶的控件無法滿足自己需求的情況寓调,這種時(shí)候锌唾,我們只能去自己去實(shí)現(xiàn)適合項(xiàng)目的控件。同時(shí)夺英,安卓也允許你去繼承已經(jīng)存在的控件或者實(shí)現(xiàn)你自己的控件以便優(yōu)化界面和創(chuàng)造更加豐富的用戶體驗(yàn)晌涕。

在Android的UI界面都是由View和ViewGroup,及其派生類組合而成的痛悯!基于AndroidUI的設(shè)計(jì)原理余黎,按道理,我們是完全可以按照自己的意愿開發(fā)出項(xiàng)目中所需要的UI界面的载萌!View是所有UI界面的基類剧劝,包括ViewGroup也是繼承自View懊蒸,如果說一個(gè)View是一個(gè)控件,那么ViewGroup就是容納這些控件的一個(gè)容器。

androidUI

根據(jù)圖充坑,作為容器的ViewGroup可以包含作為葉子節(jié)點(diǎn)的View孤紧,也可以包含作為更低層次的子ViewGroup汁讼,而子ViewGroup又可以包含下一層 的葉子節(jié)點(diǎn)的View和ViewGroup玄货。事實(shí)上,這種靈活的View層次結(jié)構(gòu)可以形成非常復(fù)雜的UI布局瓤帚,開發(fā)者可據(jù)此設(shè)計(jì)描姚、開發(fā)非常精致的UI界面涩赢。

下面就讓我來給大家介紹一下,如何來書寫這三種自定義控件轩勘!請(qǐng)隨意吐槽

  1. 自定義屬性attrs.xml的使用
  2. 基于原生控件的擴(kuò)展(例子:實(shí)現(xiàn)與系統(tǒng)字體不同的TextView)
  3. 基于組合控件的擴(kuò)展(例子:構(gòu)建可以圖文混排的LinearLayout)
  4. 自定義View(例子:波浪加載動(dòng)畫)

自定義屬性attrs.xml的使用
attrs.xml是自定義屬性的xml文件筒扒,主要作用是通過xml布局里面設(shè)置的參數(shù)然后可以傳送到程序中,我們可以理解為绊寻,attrs.xml是xml布局和java代碼中參數(shù)傳遞的橋梁花墩!

  1. 在values文件夾中新建一個(gè)attrs.xml文件
    <pre>
    <?xml version="1.0" encoding="utf-8"?>
    <resources>

    <declare-styleable name="MineTextView">
    <attr name="color" format="color"/>
    <attr name="size" format=""/>
    </declare-styleable>
    </resources>
    </pre>

  2. 新建一個(gè)類繼承自TextView并重載它的構(gòu)造方法,再聲明兩個(gè)變量來存儲(chǔ)自定義控件的屬性澄步,通過TypedArray獲取xml布局中的屬性值
    <pre>
    public class MineTextView extends TextView {
    private Context context;
    private float size;
    private int color;

    public MineTextView(Context context) {
    super(context);
    initAttrs(context,null);
    }

    public MineTextView(Context context, AttributeSet attrs) {
    super(context, attrs,0);
    initAttrs(context,attrs);
    }

    public MineTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initAttrs(context,attrs);
    }

    /**

    • 初始化Attrs參數(shù)
      */
      private void initAttrs(Context context, AttributeSet attrs) {
      this.context = context;
      if (attrs == null) return;
      TypedArray typed = context.obtainStyledAttributes(attrs, R.styleable.MineTextView);
      color = typed.getColor(R.styleable.MineTextView_color, 0X00FF00);
      size = typed.getFloat(R.styleable.MineTextView_size, 32f);
      typed.recycle();//使用完記得調(diào)用recycle
      initView();
      }

    /**

    • 初始化頁面
      */
      public void initView(){
      setTextColor(color);
      setTextSize(size);
      }
      }
      </pre>
  3. 在xml布局里面設(shè)置自定義控件屬性
    在根布局容器內(nèi)添加xmlns:app = "http://schemas.android.com/apk/res-auto"
    其中app是你自定義的命名空間冰蘑,res-auto是由程序自動(dòng)找資源,添加自定義控件進(jìn)去Layout里面村缸,再寫多一個(gè)正常的TextView用來做對(duì)比
    <pre>
    <com.marco.minecomponents.MineTextView
    android:text="Hello World!"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:color="@color/colorPrimary"
    app:size="45"/>
    <TextView
    android:text="我是正常的TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
    </pre>
    效果如下:

效果圖
  1. 基于原生控件的擴(kuò)展(例子:實(shí)現(xiàn)與系統(tǒng)字體不同的TextView)
    Android系統(tǒng)默認(rèn)支持三種字體祠肥,分別為:“****sans”, “serif”, “monospace",除此之外還可以使用其他字體文件(*.ttf)
    首先在上一個(gè)Textview的里面新建一個(gè)更改字體的方法并放進(jìn)initView里面梯皿,效果如下
    try {
    Typeface face = Typeface.createFromAsset(context.getAssets(),"/FZLTCXHJW.TTF");
    setTypeface(face);
    }catch (Exception e){
    e.printStackTrace();
    Log.i("ddd","error--->"+e.getMessage());
    }
    我把字體文件放在assets文件夾下面仇箱,之后在xml布局里面添加幾個(gè)系統(tǒng)支持的字體樣式
    <TextView
    android:text="normal"
    android:typeface="normal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
    <TextView
    android:text="sans"
    android:typeface="sans"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
    <TextView
    android:text="serif"
    android:typeface="serif"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
    <TextView
    android:text="monospace"
    android:typeface="monospace"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />
效果圖
  1. 基于組合控件的擴(kuò)展(例子:構(gòu)建圖文混排的LinearLayout)
    網(wǎng)上很多都是使用TextView.fromHtml里面的imageGetter來實(shí)現(xiàn)圖文混排,這里只是為大家簡(jiǎn)單介紹如何寫自定義控件东羹,有興趣的可以查一下相關(guān)資料剂桥!這里會(huì)給大家演示一下如何來做一個(gè)單行文本單行圖片的LinearLayoutDemo
    2.1 我們新建一個(gè)Data類用來存儲(chǔ)數(shù)據(jù)類型和View
    private int type;//內(nèi)容的類型: 1 圖片 2 文本
    private View view;
    public Data(int type, View view) {
    this.type = type;
    this.view = view;
    }
    2.2 創(chuàng)建MineLinearLayout類繼承自LinearLayout,重寫三個(gè)構(gòu)造方法和聲明一個(gè)存儲(chǔ)Data的數(shù)組作為數(shù)據(jù)源
    我們先寫一個(gè)LinearLayout布局属提,因?yàn)榭紤]到我們的LinearLayout有可能高度越界权逗,所以在xml外面要封裝多一個(gè)ScrollView
    <pre>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
    android:id="@+id/lin"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    </LinearLayout>
    </ScrollView>
    </pre>
    2.3 之后在MineLinearLayout里面將xml的布局作為root視圖,并獲取其中的LinearLayout對(duì)象, 順便說下下面代碼的三個(gè)參數(shù)代表什么意思吧垒拢!
    LayoutInflater.from(context).inflate(R.layout.layout_mine, this, true);
    第一個(gè)R.layout.layout_mine, 跳過不說
    第二個(gè)this旬迹,代表返回的View的父布局火惊,一般都是用null求类,在這里用this是因?yàn)槲冶緛砭屠^承了一個(gè)LinearLayout
    第三個(gè)是一個(gè)boolean類型,是否將返回的View作為root視圖
    之后再在MineLinearLayout里面完善添加數(shù)據(jù)屹耐,更新數(shù)據(jù)尸疆,刪除數(shù)據(jù)的操作
    <pre>// 初始化頁面
    public void initView(Context context) {
    setOrientation(VERTICAL);//豎向分布
    LayoutInflater.from(context).inflate(R.layout.layout_mine, this, true);
    lin = (LinearLayout)findViewById(R.id.lin);
    }
    // 更新頁面public void updateView() {
    for (Data data : datas) {
    lin.addView(data.getView());
    }
    }
    // 移除View
    public void removeView(int position) {
    if (position < datas.size() && position > 0) {
    lin.removeView(datas.get(position).getView());
    datas.remove(position); }
    }
    // 重設(shè)頁面
    public void resetData() {
    lin.removeAllViews();
    datas.clear();
    }
    // 設(shè)置頁面數(shù)據(jù)
    public void setData(ArrayList<Data> datas) {
    resetData();
    this.datas.addAll(datas);
    updateView();
    }
    // 添加頁面數(shù)據(jù)
    public void addData(Data data) {
    datas.add(data);
    lin.addView(data.getView());
    }</pre>
    2.4 在MainActivity的布局里面添加自定義控件,并添加測(cè)試數(shù)據(jù)
    <pre><com.marco.minecomponents.MineLinearLayout
    android:id="@+id/mine"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"/></pre>
    <pre>public void initData(){
    ArrayList<Data> datas = new ArrayList<>();
    datas.add(new Data(0,getTextView()));
    datas.add(new Data(1,getImageView()));
    datas.add(new Data(0,getTextView()));
    datas.add(new Data(1,getImageView()));
    datas.add(new Data(0,getTextView()));
    datas.add(new Data(1,getImageView()));
    lin.setData(datas);
    }

    public View getTextView() {
    TextView tv = new TextView(this);
    tv.setText("text");
    tv.setTextSize(32);
    tv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    tv.setPadding(8, 8, 8, 8);
    return tv;
    }

    public View getImageView() {
    ImageView img = new ImageView(this);
    img.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    img.setBackgroundResource(android.R.color.transparent);
    img.setImageResource(R.drawable.demo);
    return img;
    }
    </pre>

效果圖
  1. 自定義View(例子:波浪動(dòng)畫)
    制作一個(gè)自定義的波浪動(dòng)畫惶岭,首先是需要先畫一條曲線寿弱,我們需要使用到Android繪圖Api,其中比較重要的是Paint按灶,Path症革,和重寫onDraw方法。而繪制波浪主要是用Path提供的quadTo方法來繪制貝塞爾曲線鸯旁,其中quadTo的四個(gè)參數(shù)噪矛,分別為起始點(diǎn)的xy坐標(biāo)和終點(diǎn)的xy坐標(biāo)量蕊!在設(shè)置的時(shí)候,要把頂點(diǎn)和終點(diǎn)計(jì)算出來艇挨。
    3.1 聲明要用的變量残炮,通過onSizeChange方法獲取視圖寬高,設(shè)置畫筆缩滨,在onDraw里面設(shè)置路徑势就,根據(jù)路徑來繪制曲線
    <pre>
    // 初始化畫筆
    private void initPaint() {
    paint = new Paint();
    paint.setStrokeWidth(14);//設(shè)置畫筆寬度
    paint.setColor(Color.argb(70, 255, 255, 255));
    paint.setAntiAlias(true);//抗鋸齒
    paint.setStyle(Paint.Style.STROKE);//實(shí)線
    path = new Path();
    }

    @Override
    protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

     //畫路徑
     path.moveTo(0, mHeight / 2);
     path.quadTo(mWidth / 8, mHeight / 2 - waveHeight, mWidth / 4, mHeight / 2);
     path.quadTo(mWidth * 3 / 8, mHeight / 2 + waveHeight, mWidth / 2, mHeight / 2);
     path.quadTo(mWidth * 5 / 8, mHeight / 2 - waveHeight, mWidth * 3 / 4, mHeight / 2);
     path.quadTo(mWidth * 7 / 8, mHeight / 2 + waveHeight, mWidth, mHeight / 2);
     canvas.drawPath(path, paint);
    

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    //獲取屏幕高度和寬度
    this.mHeight = h;
    this.mWidth = w;
    }
    </pre>

計(jì)算曲線位置
波浪效果

3.2 繪制閉合曲線
<pre>
paint.setStyle(Paint.Style.FILL);
path.lineTo(mWidth,mHeight);
path.lineTo(0,mHeight);
path.close();</pre>

3.3 下一步我們要做的就是讓路徑運(yùn)動(dòng)起來,波浪其實(shí)就是曲線向前運(yùn)動(dòng)而已脉漏!那么我們考慮如果有兩倍長(zhǎng)的曲線苞冯,當(dāng)向前運(yùn)動(dòng)的距離和寬度一致的時(shí)候,是不是就可以模擬一個(gè)波浪的動(dòng)畫了侧巨!
下面我們來看一張圖

草圖

看右上角抱完,兩端波浪組成的,所以起始位置就在(0-mWidth+movePath刃泡,mHeight/2)
而第一段波浪因?yàn)檫€在屏幕外巧娱,所以需要涉及到橫坐標(biāo)的都要家還是那個(gè)movePath-mWidth,第二段加上movePath就可以了
那么烘贴,代碼經(jīng)過修改后就變成這樣:::
<pre> //畫路徑
path.moveTo(movePath - mWidth, mHeight / 2);
path.quadTo(mWidth / 8 + movePath - mWidth, mHeight / 2 - waveHeight, mWidth / 4 + movePath - mWidth, mHeight / 2);
path.quadTo(mWidth * 3 / 8 + movePath - mWidth, mHeight / 2 + waveHeight, mWidth / 2 + movePath - mWidth, mHeight / 2);
path.quadTo(mWidth * 5 / 8 + movePath - mWidth, mHeight / 2 - waveHeight, mWidth * 3 / 4 + movePath - mWidth, mHeight / 2);
path.quadTo(mWidth * 7 / 8 + movePath - mWidth, mHeight / 2 + waveHeight, mWidth + movePath - mWidth, mHeight / 2);
//第二段
path.quadTo(mWidth / 8 + movePath, mHeight / 2 - waveHeight, mWidth / 4 + movePath, mHeight / 2);
path.quadTo(mWidth * 3 / 8 + movePath, mHeight / 2 + waveHeight, mWidth / 2 + movePath, mHeight / 2);
path.quadTo(mWidth * 5 / 8 + movePath, mHeight / 2 - waveHeight, mWidth * 3 / 4 + movePath, mHeight / 2);
path.quadTo(mWidth * 7 / 8 + movePath, mHeight / 2 + waveHeight, mWidth + movePath, mHeight / 2);
//閉合曲線
path.lineTo(mWidth + movePath, mHeight);
path.lineTo(movePath - mWidth, mHeight);
path.close();
//繪制曲線
canvas.drawPath(path, paint);</pre>
3.4 最后調(diào)用invalidate();重繪就可以了禁添,至于動(dòng)圖我就不傳了,不知道怎么傳=白佟@锨獭!囧

Paste_Image.png

最終結(jié)語:其實(shí)自定義控件博大精深锻离,遠(yuǎn)遠(yuǎn)不止這么簡(jiǎn)單铺峭!這里只是說了一下我了解到的一下簡(jiǎn)單的技巧!自定義View里面的比較重要的方法例如汽纠,onMeasure卫键,onLayout,矩陣變換虱朵,我都沒說(我也沒懂)莉炉!大家將就著看吧,如果哪里有寫錯(cuò)或者不明白的碴犬,歡迎各種丟香蕉丟西瓜皮絮宁!

Demo地址:https://github.com/Mark911105/MineComponents.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市服协,隨后出現(xiàn)的幾起案子绍昂,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,941評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件窘游,死亡現(xiàn)場(chǎng)離奇詭異卖陵,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)张峰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門泪蔫,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人喘批,你說我怎么就攤上這事撩荣。” “怎么了饶深?”我有些...
    開封第一講書人閱讀 165,345評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵餐曹,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我敌厘,道長(zhǎng)台猴,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,851評(píng)論 1 295
  • 正文 為了忘掉前任俱两,我火速辦了婚禮饱狂,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘宪彩。我一直安慰自己休讳,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評(píng)論 6 392
  • 文/花漫 我一把揭開白布尿孔。 她就那樣靜靜地躺著俊柔,像睡著了一般。 火紅的嫁衣襯著肌膚如雪活合。 梳的紋絲不亂的頭發(fā)上雏婶,一...
    開封第一講書人閱讀 51,688評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音白指,去河邊找鬼留晚。 笑死,一個(gè)胖子當(dāng)著我的面吹牛侵续,可吹牛的內(nèi)容都是我干的倔丈。 我是一名探鬼主播憨闰,決...
    沈念sama閱讀 40,414評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼状蜗,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了鹉动?” 一聲冷哼從身側(cè)響起轧坎,我...
    開封第一講書人閱讀 39,319評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎泽示,沒想到半個(gè)月后缸血,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蜜氨,經(jīng)...
    沈念sama閱讀 45,775評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年捎泻,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了飒炎。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,096評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡笆豁,死狀恐怖郎汪,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情闯狱,我是刑警寧澤煞赢,帶...
    沈念sama閱讀 35,789評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站哄孤,受9級(jí)特大地震影響照筑,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜瘦陈,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評(píng)論 3 331
  • 文/蒙蒙 一凝危、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧晨逝,春花似錦媒抠、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至昏翰,卻和暖如春苍匆,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背棚菊。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評(píng)論 1 271
  • 我被黑心中介騙來泰國(guó)打工浸踩, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人统求。 一個(gè)月前我還...
    沈念sama閱讀 48,308評(píng)論 3 372
  • 正文 我出身青樓检碗,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親码邻。 傳聞我的和親對(duì)象是個(gè)殘疾皇子折剃,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容