自訂view(使用EditTetx實現記事本特效)

來源:互聯網
上載者:User

標籤:

先看一下:

思路: 建立一個類,繼承自EditText,在onDraw方法中繪製我們的底線,通過螢幕的高度和每行控制項的高度的比值得出螢幕中應該繪製多少行底線,再來實現一些自訂的屬性,設定控制項基本的邊距和內容邊距就ok了 ,過程很簡單的,代碼的注釋寫的很詳細,有需要的同學可以去閱讀一下

自訂類MyNoteEditText.class

package com.wjt.day43_01_mynoteedittext;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.view.Gravity;import android.widget.EditText;public class MyNoteEditText extends EditText{   private int lineColor = Color.RED  ;   private int lineStrokWidth = 1 ;   private int padding = 10 ;public MyNoteEditText(Context context, AttributeSet attrs) {super(context, attrs);//這句話是讓每一行的輸入的資料都位於他的左上部分setGravity(Gravity.TOP);TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyNoteEditText);lineColor = array.getColor(R.styleable.MyNoteEditText_lineColor, lineColor);lineStrokWidth = (int) array.getDimension(R.styleable.MyNoteEditText_lineStrokWidth, lineStrokWidth);padding = (int) array.getDimension(R.styleable.MyNoteEditText_padding, padding);array.recycle();//實現內容和劃線部分的一一對應setPadding(padding, 0, padding, 0);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);//1,建立一個畫筆Paint paint = new Paint();paint.setAntiAlias(true);paint.setColor(lineColor);paint.setStrokeWidth(lineStrokWidth);//2,擷取當前整個控制項的寬高    int viewHeight = getHeight();int viewWidth = getWidth() ;//3,擷取EditText中每一行的寬度int lineHeight = getLineHeight();//4,通過計算螢幕中一共能放多少行int pageLineCounts = viewHeight/lineHeight ;//5,使用畫布劃線for (int i = 0; i < pageLineCounts; i++) {canvas.drawLine(padding, (i+1)*lineHeight, viewHeight - padding, (i+1)*lineHeight, paint);}//6,實現當文字寫到下一頁的時候繼續劃線int textLineCount =getLineCount() ; if (textLineCount > pageLineCounts) {for (int i = pageLineCounts; i < textLineCount; i++) {canvas.drawLine(padding, (i+1)*lineHeight, viewHeight - padding, (i+1)*lineHeight, paint);}}}}

 自訂屬性部分attrs.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name = "NoteEditText">        <attr name = "lineColor" format="color|reference"/>        <attr name = "lineStrokeWidth" format="dimension|reference"/>        <attr name = "padding" format="dimension|reference"/>    </declare-styleable></resources>

  

 

自訂view(使用EditTetx實現記事本特效)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.