Android TextView 文本自動對齊
自定義View顯示文本
網上就有達人采用自定義View來解決這個問題,我做了實驗並總結了一下:
自定義View的步驟:
1)繼承View類或其子類,例子繼承了TextView類;
2)寫構造函數,通過XML獲取屬性(這一步中可以自定義屬性,見例程);
3)重寫父類的某些函數,一般都是以on開頭的函數,例子中重寫了onDraw()和onMeasure()函數;
=========================StartCustomTextView.java=============================
public class StartCustomTextView extends TextView { public static int m_iTextHeight; //文本的高度 public static int m_iTextWidth;//文本的寬度 private Paint mPaint = null; private String string=""; private float LineSpace = 0;//行間距 private int left_Margin; private int right_Margin; private int bottom_Margin; public StartCustomTextView(Context context, AttributeSet set) { super(context,set); DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); TypedArray typedArray = context.obtainStyledAttributes(set, R.styleable.CYTextView); int width = displayMetrics.widthPixels; left_Margin = 29; right_Margin = 29; bottom_Margin = 29; width = width - left_Margin -right_Margin; float textsize = typedArray.getDimension(R.styleable.CYTextView_textSize, 34); int textcolor = typedArray.getColor(R.styleable.CYTextView_textColor, getResources().getColor(R.color.white)); float linespace = typedArray.getDimension(R.styleable.CYTextView_lineSpacingExtra, 15); int typeface = typedArray.getColor(R.styleable.CYTextView_typeface, 0); typedArray.recycle(); //設置 CY TextView的寬度和行間距www.linuxidc.com m_iTextWidth=width; LineSpace=linespace; // 構建paint對象 mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setColor(textcolor); mPaint.setTextSize(textsize); switch(typeface){ case 0: mPaint.setTypeface(Typeface.DEFAULT); break; case 1: mPaint.setTypeface(Typeface.SANS_SERIF); break; case 2: mPaint.setTypeface(Typeface.SERIF); break; case 3: mPaint.setTypeface(Typeface.MONOSPACE); break; default: mPaint.setTypeface(Typeface.DEFAULT); break; } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); char ch; int w = 0; int istart = 0; int m_iFontHeight; int m_iRealLine=0; int x=2; int y=30; Vector m_String=new Vector(); FontMetrics fm = mPaint.getFontMetrics(); m_iFontHeight = (int) Math.ceil(fm.descent - fm.top) + (int)LineSpace;//計算字體高度(字體高度+行間距) for (int i = 0; i < string.length(); i++) { ch = string.charAt(i); float[] widths = new float[1]; String srt = String.valueOf(ch); mPaint.getTextWidths(srt, widths); if (ch == '\n'){ m_iRealLine++; m_String.addElement(string.substring(istart, i)); istart = i + 1; w = 0; }else{ w += (int) (Math.ceil(widths[0])); if (w > m_iTextWidth){ m_iRealLine++; m_String.addElement(string.substring(istart, i)); istart = i; i--; w = 0; }else{ if (i == (string.length() - 1)){ m_iRealLine++; m_String.addElement(string.substring(istart, string.length())); } } } } m_iTextHeight=m_iRealLine*m_iFontHeight+2; canvas.setViewport(m_iTextWidth, m_iTextWidth); for (int i = 0, j = 0; i < m_iRealLine; i++, j++) { canvas.drawText((String)(m_String.elementAt(i)), x, y+m_iFontHeight * j, mPaint); } } protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredHeight = measureHeight(heightMeasureSpec); int measuredWidth = measureWidth(widthMeasureSpec); this.setMeasuredDimension(measuredWidth, measuredHeight); LayoutParams layout = new LinearLayout.LayoutParams(measuredWidth,measuredHeight); layout.leftMargin= left_Margin; layout.rightMargin= right_Margin; layout.bottomMargin= bottom_Margin; this.setLayoutParams(layout); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } private int measureHeight(int measureSpec) { int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); // Default size if no limits are specified. initHeight(); int result = m_iTextHeight; if (specMode == MeasureSpec.AT_MOST){ // Calculate the ideal size of your // control within this maximum size. // If your control fills the available // space return the outer bound. result = specSize; }else if (specMode == MeasureSpec.EXACTLY){ // If your control can fit within these bounds return that value. // result = specSize; } return result; } private void initHeight() { //設置 CY TextView的初始高度為0 m_iTextHeight=0; //大概計算 CY TextView所需高度 FontMetrics fm = mPaint.getFontMetrics(); int m_iFontHeight = (int) Math.ceil(fm.descent - fm.top) + (int)LineSpace; int line=0; int istart=0; int w=0; for (int i = 0; i < string.length(); i++) { char ch = string.charAt(i); float[] widths = new float[1]; String srt = String.valueOf(ch); mPaint.getTextWidths(srt, widths); if (ch == '\n'){ line++; istart = i + 1; w = 0; }else{ w += (int) (Math.ceil(widths[0])); if (w > m_iTextWidth){ line++; istart = i; i--; w = 0; }else{ if (i == (string.length() - 1)){ line++; } } } } m_iTextHeight=(line)*m_iFontHeight+2; } private int measureWidth(int measureSpec) { int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); // Default size if no limits are specified. int result = 500; if (specMode == MeasureSpec.AT_MOST){ // Calculate the ideal size of your control // within this maximum size. // If your control fills the available space // return the outer bound. result = specSize; }else if (specMode == MeasureSpec.EXACTLY){ // If your control can fit within these bounds return that value. result = specSize; } return result; } public void SetText(String text) { string = text; // requestLayout(); // invalidate(); } }
=======================attrs.xml===============================
該文件是自定義的屬性,放在工程的res/values下
<resources> <attr name="textwidth" format="integer"/> <attr name="typeface"> <enum name="normal" value="0"/> <enum name="sans" value="1"/> <enum name="serif" value="2"/> <enum name="monospace" value="3"/> </attr> <declare-styleable name="CYTextView"> <attr name="textwidth" /> <attr name="textSize" format="dimension"/> <attr name="textColor" format="reference|color"/> <attr name="lineSpacingExtra" format="dimension"/> <attr name="typeface" /> </declare-styleable> </resources>
=======================main.xml==========================
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:Andro Android:layout_width="320px" Android:layout_height="320px" Android:background="#ffffffff" > <LinearLayout xmlns:Andro Android:orientation="vertical" Android:layout_width="fill_parent" Android:layout_height="fill_parent"> <com.cy.CYTextView.CYTextView xmlns:cy="https://schemas.Android.com/apk/res/ com.cy.CYTextView " Android: Android:layout_height="wrap_content" Android:layout_width="wrap_content" cy :textwidth="320" cy :textSize="24sp" cy :textColor="#aa000000" cy :lineSpacingExtra="15sp" cy :typeface="serif"> </com. cy .CYTextView.CYTextView> </LinearLayout> </ScrollView>
藍色代碼即為自定義View,其中以cy命名空間開頭的屬性是自定義屬性;
=======================Main.java=============================
public class Main extends Activity { CYTextView mCYTextView; String text = "Android提供了精巧和有力的組件化模型構建用戶的UI部分。主要是基於布局類:View和 ViewGroup。在此基礎上,android平台提供了大量的預製的View和xxxViewGroup子 類,即布局(layout)和窗口小部件(widget)。可以用它們構建自己的UI。"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.main); mCYTextView = (CYTextView)findViewById(R.id.mv); mCYTextView.SetText(text); } }
https://blog.csdn.net/furongkang/article/details/7625814
最後更新:2017-04-02 16:48:03
上一篇:
Huffman 編碼壓縮算法
下一篇:
struts2中改變struts.xml默認路徑
windows中修改catalina.sh上傳到linux執行報錯This file is needed to run this program
poj 1192 最優聯通子集 簡單dp
mysql審計開啟--兩種方法
深入並行:從生產者到消費者模型深度理解Oracle的並行
1-9這9個數字劃分成三個3位數,第一個分別是第二、三個的2倍,3倍,用程序劃分
看過三生三世的桃花,你吃過淩晨三點的桃子嗎?
java.lang.OutOfMemoryError: Java heap space 解決方法
獲得CPU溫度的函數
第一章:什麼是管理
android sdk 編譯--如何將源代碼加入android.jar,以及make原理 2