EditText小記
http://www.cnblogs.com/endure/p/3690443.html
Android字體陰影
strings.xml文件定義字符串中的標籤
Android TextView 自動換行問題
關於android軟鍵盤enter鍵的替換與事件監聽
軟件盤的界面替換隻有一個屬性android:imeOptions,這個屬性的能夠取的值有normal,actionUnspecified,actionNone,actionGo,actionSearch,actionSend,actionNext,actionDone,例如當值爲actionNext時enter鍵外觀變成一個向下箭頭,而值爲actionDone時enter鍵外觀則變成了「完成」兩個字。
咱們也能夠重寫enter的事件,方法以下: html
TextView editText = new TextView(this); editText.setOnEditorActionListene( newTextView.OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event){ if (actionId == EditorInfo.IME_ACTION_SEND) { // 在這裏編寫本身想要實現的功能 } return false; } });
另附: 攔截HOME按鍵
Android如何顯示音標
http://marshal.easymorse.com/archives/4087
EditText設置光標顏色
android:textCursorDrawable="@null"
EditText設置光標位置問題
EditText中有一些預置文本的時候,想把光標調到最前面,一開始是使用的setSelection(0),結果發如今三星P1000上面有問題。通過研究發現須要先調用EditText.requestFocus(),再調用setSelection(0)。不然的話,在2.x的機器上有問題,但3.x上面是好着的。
EditText橫屏時,彈出軟件盤時不進行全屏
在使用EditText進行文本輸入時,若不進行特殊的設置,使用Android自帶的軟鍵盤,該軟鍵盤會佔用整個界面,那麼,如何讓鍵盤只佔用屏幕的一部分呢? android
<EditText android:id="@+id/text1" android:layout_width="150dip" android:layout_height="wrap_content" android:imeOptions="flagNoExtractUi"/>
使用android:imeOptinos可對Android自帶的軟鍵盤進行一些界面上的設置: canvas
android:imeOptions="flagNoExtractUi" //使軟鍵盤不全屏顯示,只佔用一部分屏幕 同時,這個屬性還能控件軟鍵盤右下角按鍵的顯示內容,默認狀況下爲回車鍵 android:imeOptions="actionNone" //輸入框右側不帶任何提示 android:imeOptions="actionGo" //右下角按鍵內容爲'開始' android:imeOptions="actionSearch" //右下角按鍵爲放大鏡圖片,搜索 android:imeOptions="actionSend" //右下角按鍵內容爲'發送' android:imeOptions="actionNext" //右下角按鍵內容爲'下一步' android:imeOptions="actionDone" //右下角按鍵內容爲'完成'
同時,可能EditText添加相應的監聽器,捕捉用戶點擊了軟鍵盤右下角按鈕的監聽事件,以便進行處理。 數組
editText.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { Toast.makeText(MainActivity.this, "text2", Toast.LENGTH_SHORT).show(); return false; } });
在TextView控件中單擊連接彈出Activity
http://blog.csdn.net/nokiaguy/article/details/6835916
TextView中作文字按鈕實現點擊事件
http://www.eoeandroid.com/thread-168290-1-1.html
Android使用TextView實現無下劃線超連接
http://orgcent.com/android-textview-no-underline-hyperlink/
文本框實現搜索和清空效果
http://407827531.iteye.com/blog/1114592
爲TextView添加陰影
values/styles ide
<style name="AudioFileInfoOverlayText"> <item name="android:paddingLeft">4px</item> <item name="android:paddingBottom">4px</item> <item name="android:textColor">#ffffffff</item> <item name="android:textSize">12sp</item> <item name="android:shadowColor">#ff00ff00</item> <item name="android:shadowDx">5</item> <item name="android:shadowDy">3</item> <item name="android:shadowRadius">6</item> </style> <TextView android:id="@+id/info" android:layout_width="fill_parent" android:layout_height="wrap_content" style="@style/AudioFileInfoOverlayText" android:text="aaaa" android:gravity="center" />
如何將TextView中的中文設置成粗體?
在xml文件中使用android:textStyle="bold" 能夠將英文設置成粗體,可是不能將中文設置成粗體,將中文設置成粗體的方法是:
TextView tv = (TextView)findViewById(R.id.TextView01);
TextPaint tp = tv.getPaint();
tp.setFakeBoldText(true);
其餘還有:
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24f);//設置成24sp
textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));//可能中文加粗無效
textView.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC));//可能中文無效
textView.setText(Html.fromHtml("<u>"+texts[i]+"</u>"));//下劃線
textView.setTypeface(Typeface.MONOSPACE,Typeface.ITALIC);//斜體,中文有效
textView.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG );//中間加橫線
textView.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG );//底部加橫線
android:ellipsize = "end" 省略號在結尾
android:ellipsize = "start" 省略號在開頭
android:ellipsize = "middle" 省略號在中間
android:ellipsize = "marquee" 跑馬燈
android:singleline = "true"
固然也能夠用代碼語句:
tv.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
tv.setEllipsize(TextUtils.TruncateAt.valueOf("START"));
tv.setEllipsize(TextUtils.TruncateAt.valueOf("MIDDLE"));
tv.setEllipsize(TextUtils.TruncateAt.valueOf("MARQUEE"));
tv.setSingleLine(true);
ellipsize和lines
<TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#FF00FF00" android:textSize="20px" android:lines="4" android:ellipsize="end" android:text="Automatic Target Mode: using existing emulator running compatible AVD.Application already deployed. No need to reinstall.Application already deployed. No need to reinstall.Application already deployed. No need to reinstall" />
不要將ellipsize和lines一塊兒使用,不然會讓人疑惑。像上面的代碼會顯示幾行文字呢?
android:lines感受是用於顯示文字的行數,事實上是不確切的。假如文字不知足夠的行數呢?android:lines更適合用於設置TextView的高度,像上面的代碼指定了TextView的高度能夠顯示4行文字,若是文字不滿4行,則TextView仍舊顯示4行的高度!
android:ellipsize用於當文字過長時縮略顯示,默認會縮略顯示2行!若是和android:singleLine="true"一塊兒使用則顯示一行;但不要覺得和android:lines="4"或和android:maxLines="4"一塊兒使用會顯示4行,當試驗過了才知道仍然顯示2行!
動態顯示隱藏密碼輸入框的內容
et.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); // display password text, for example "123456"
et.setTransformationMethod(PasswordTransformationMethod.getInstance());// hide password, display "."
如何對EditText輸入字數作限制?
private EditText mEditText ; mEditText = (EditText) findViewById(R.id.mEditText ); /** 限制字數 */ mEditText .addTextChangedListener(new TextWatcher() { private CharSequence temp; private int selectionStart ; private int selectionEnd ; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { temp = s; } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { selectionStart = mEditText .getSelectionStart(); selectionEnd = mEditText .getSelectionEnd(); Log.d(TAG,""+selectionStart); if (temp.length() > 8) { Toast.makeText(MAUpdateAty.this, "字數不能超過8個", Toast.LENGTH_SHORT).show(); s.delete(selectionStart-1, selectionEnd); int tempSelection = selectionStart; mEditText .setText(s); mEditText .setSelection(tempSelection); } Log.d(TAG," "+selectionEnd); } });
或者試試這個:
private TextWatcher mTextWatcher = new TextWatcher(){ Toast mToast = null; public void beforeTextChanged(CharSequence s, int start, int count,int after) { } public void onTextChanged(CharSequence s, int start, int before,int count) { } public void afterTextChanged(Editable s) { int nSelStart = 0; int nSelEnd = 0; boolean nOverMaxLength = false; nSelStart = mEditText.getSelectionStart(); nSelEnd = mEditText.getSelectionEnd(); nOverMaxLength = (s.length() > Constants.MAX_TEXT_INPUT_LENGTH) ? true : false; if(nOverMaxLength){ if(null == mToast){ mToast = Toast.makeText(mContext, R.string.IDS_MSG_TEXT_OVER_MAXLENGTH, Toast.LENGTH_SHORT); } mToast.show(); s.delete(nSelStart - 1, nSelEnd); mEditText.setTextKeepState(s);//請讀者注意這一行,保持光標原先的位置,而 mEditText.setText(s)會讓光標跑到最前面,就算是再加mEditText.setSelection(nSelStart) 也不起做用 } } };
或者試試這個:
用代碼控制,能夠用InputFilter限定20個字符:
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
或者這個:
android:maxLength來設置輸入的最大長度
控制輸入小數的位數
// 設置小數位數控制 InputFilter lengthfilter = new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { // 刪除等特殊字符,直接返回 if ("".equals(source.toString())) { return null; } String dValue = dest.toString(); String[] splitArray = dValue.split("\\."); if (splitArray.length > 1) { String dotValue = splitArray[1]; int diff = dotValue.length() + 1 - digLength; if (diff > 0) { return source.subSequence(start, end - diff); } } return null; } }; inputEdit.setFilters(new InputFilter[] { lengthfilter });
一 . 設置焦點
若是在單擊某個 EditText 的時候想讓其餘的 EditText 得到輸入的焦點,那麼可使用下面的語句,
getCurrentFocus().setFocusable(false); getCurrentFocus().setFocusableInTouchMode(false);
而要得到焦點的 EditText :
mSearchEdit.setFocusable(true); mSearchEdit.setFocusableInTouchMode(true); mSearchEdit.requestFocus();
二 . 設置輸入格式過濾器
爲 EditText 設置輸入的過濾器。InputFilter, 首先要注意的是對一個 EditText 的對象設置 setFilters(InputFilter[] filters) ,其參數是一個 inputFilter 數組,即對一個 EditText 你能夠同時設置多個輸入過濾器。而咱們平時用的時候通常設置一個過濾器就能夠了,因此能夠做以下使用(以輸入數字爲例):
InputFilter[] mDigitsFilters = new InputFilter[1];
mDigitsFilters[0] = new DigitsKeyListener(true, true);
ps: DigitsKeyListener 第一個參數是 Sign, 若是設置爲 true ,表示容許在數字最左端有負號,不然只能輸入正數;第二個參數是 decimal, 若是設置爲 true, 表示容許在數字中有一個小數點存在。
最後 setFilters(mDigitsFilters); 就 OK 了,
InputFilter 是一個接口,其實現的子類有:
DateKeyListener, DateTimeKeyListener, DialerKeyListener, DigitsKeyListener, InputFilter.AllCaps, InputFilter.LengthFilter, LoginFilter, LoginFilter.PasswordFilterGMail, LoginFilter.UsernameFilterGMail, LoginFilter.UsernameFilterGeneric, NumberKeyListener, TimeKeyListener
DateKeyListener For entering dates in a text field.
DateTimeKeyListener For entering dates and times in the same text field.
DialerKeyListener For dialing-only text entry
DigitsKeyListener For digits-only text entry
InputFilter.AllCaps This filter will capitalize all the lower case letters that are added through edits.
InputFilter.LengthFilter This filter will constrain edits not to make the length of the text greater than the specified length.
LoginFilter Abstract class for filtering login-related text (user names and passwords)
LoginFilter.PasswordFilterGMail This filter is compatible with GMail passwords which restricts characters to the Latin-1 (ISO8859-1) char set.
LoginFilter.UsernameFilterGMail This filter rejects characters in the user name that are not compatible with GMail account creation.
LoginFilter.UsernameFilterGeneric This filter rejects characters in the user name that are not compatible with Google login.
NumberKeyListener For numeric text entry
TimeKeyListener For entering times in a text field.
根據解釋應該不難理解,根據你本身的須要選擇吧。
實例:
EditText與InputFilter實現文本對比
此功能相似於臨摹。已知被臨摹的字符串,將字符串與EditText中輸入進行
對比,輸入錯誤,則用「×」替換所輸入的字符。
import android.app.Activity; import android.os.Bundle; import android.text.InputFilter; import android.text.Spanned; import android.util.Log; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MyFilterTest extends Activity { /** Called when the activity is first created. */ TextView myText; EditText myEdit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final String str = "Hello,Android!"; myText=(TextView)findViewById(R.id.myText); myText.setText(str); myEdit=(EditText)findViewById(R.id.myEdit); myEdit.setFilters(new InputFilter[]{ new MyInputFilter(str) }); } public class MyInputFilter implements InputFilter{ String str=null; public MyInputFilter(String str){ this.str=str; } @Override public CharSequence filter(CharSequence src, int start, int end, Spanned dest, int dstart, int dend) { // TODO Auto-generated method stub String ch=null; String TAG="Filter"; Log.w(TAG,"src:"+src+";start:"+start+";end:"+end); Log.w(TAG,"dest:"+dest+";dstart:"+dstart+";dend:"+dend); if(dest.length()<str.length()){ ch=str.substring(dstart+start, dstart+end); }else{ return dest.subSequence(dstart, dend); } if(ch.equals(src)){ Toast.makeText(MyFilterTest.this, "match", Toast.LENGTH_SHORT).show(); return dest.subSequence(dstart, dend)+src.toString(); }else{ Toast.makeText(MyFilterTest.this, "mismatch", Toast.LENGTH_SHORT).show(); return dest.subSequence(dstart, dend)+"×"; } } } }
參見其餘:
http://www.blogjava.net/improviser/archive/2010/11/08/337501.html
http://wang-peng1.iteye.com/blog/1022523
如何設置EditText隱藏鍵盤 ?
(EditText)mMarket.setInputType(0);
如何設置EditText不被輸入法遮蓋 ?
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
如何解決軟鍵盤彈出引發的各類不適
如何隱藏Activity剛進來焦點在EditText時顯示輸入鍵盤?
一個Activity剛進來時焦點在EditText時,會彈出輸入的鍵盤,這不是我想要的,而後就想辦法隱藏掉輸入鍵盤。嘗試了EditText的clearFocus不行,也試過其它控件ruquestFocus也不行,用隱藏鍵盤的方法 http://mingkg21.iteye.com/blog/548642
不行。試試下面這種:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
這個方法的意思是,只有點擊EditText時纔會彈出輸入鍵盤。
教程:如何控制輸入法軟鍵盤的出現方式
TextView實現多行本文滾動
Android中咱們爲了實現文本的滾動能夠在ScrollView中嵌入一個TextView,其實TextView本身也能夠實現多行滾動的,畢竟ScrollView必須只能有一個直接的子類佈局。只要在layout中簡單設置幾個屬性就能夠輕鬆實現
<TextView
android:id="@+id/tvCWJ"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" <!--垂直滾動條 -->
android:singleLine="false" <!--實現多行 -->
android:maxLines="15" <!--最多不超過15行 -->
android:textColor="#FF0000"
/>
固然咱們爲了讓TextView動起來,還須要用到TextView的setMovementMethod方法設置一個滾動實例,代碼以下
TextView tv = (TextView)findViewById(R.id.tvCWJ);
tv.setMovementMethod(ScrollingMovementMethod.getInstance());
android實現TextView垂直或水平滾動
設置EditText顯示或隱藏密碼
if (isChecked) { System.out.println("checked"); // 顯示密碼 password_edit.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } else { System.out.println("not checked"); // 隱藏密碼 password_edit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); }
EditView小寫轉大寫
final EditText input = new EditText(this); InputFilter[] FilterArray = new InputFilter[1]; FilterArray[0] = new InputFilter.AllCaps(); input.setFilters(FilterArray);
阻止EditText一開始就得到焦點
程序在加載視圖時老是會把輸入的焦點自動移動到第一個輸入框(這樣致使在某些機器上程序一啓動就彈出輸入法框,非常不爽),如何讓他不得到焦點呢?
EditText.setSelected(false);
上述命令是不行的。
clearFocus() 纔是能夠的。
若是你是用AutoCompleteTextView
<!-- Dummy item to prevent AutoCompleteTextView from receiving focus --> <!--最簡單的方法是在TextView的父容器(一般是LinearLayout)中設置android:focusable="true" android:focusableInTouchMode="true",這樣就把焦點從EditText上移走了。--> <LinearLayout android:focusable="true" android:focusableInTouchMode="true" android:layout_width="0px" android:layout_height="0px"> <!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component to prevent the dummy from receiving focus again --> <AutoCompleteTextView android:id="@+id/text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:nextFocusUp="@+id/text" android:nextFocusLeft="@+id/text"/> </LinearLayout>
完全隱藏軟鍵盤
EditText et=(EditText)findViewById(R.id.edit); et.setInputType(InputType.TYPE_DATETIME_VARIATION_NORMAL);
tv.setCompoundDrawables()不起做用?
Drawable leftDrawable; leftDrawable= getResources().getDrawable(R.drawable.left_drawable); // user setCompoundDrawables() method , you must call Drawable.setBounds() method !Or the Image can't show . leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight()); mTextView.setCompoundDrawables(leftDrawable, null, null, null);
其實就是android:drawableLeft="@drawable/icon"啦!
Enter鍵圖標的設置
軟鍵盤的Enter鍵默認顯示的是「完成」文本,咱們知道按Enter建表示前置工做已經準備完畢了,要去什麼什麼啦。好比,在一個搜索中,咱們輸入要搜索的文本,而後按Enter表示要去搜索了,可是默認的Enter鍵顯示的是「完成」文本,看着不太合適,不符合搜索的語義,若是能顯示「搜索」兩個字或者顯示一個表示搜索的圖標多好。事實證實咱們的想法是合理的,Android也爲咱們提供的這樣的功能。經過設置android:imeOptions來改變默認的「完成」文本。這裏舉幾個經常使用的常量值:
<EditText android:id="@+id/edit_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:imeOptions="actionSearch"/>
EditText的取值、全選、部分選擇、獲取選中文本
下面經過一個例子來演示EditText的取值、全選、部分選擇和獲取選中文本.main.xml以下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <EditText android:id="@+id/edit_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:imeOptions="actionSearch"/> <Button android:id="@+id/btn_get_value" android:text="取值" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/btn_all" android:text="全選" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/btn_select" android:text="從第2個字符開始選擇" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/btn_get_select" android:text="獲取選中文本" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
代碼:
package com.flysnow; import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.Selection; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.widget.TextView.OnEditorActionListener; /** * EditText演示 * @author 飛雪無情 * @since 2010-11-29 */ public class HelloEditText extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final EditText editText=(EditText)findViewById(R.id.edit_text); //監聽回車鍵 editText.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { Toast.makeText(HelloEditText.this, String.valueOf(actionId), Toast.LENGTH_SHORT).show(); return false; } }); //獲取EditText文本 Button getValue=(Button)findViewById(R.id.btn_get_value); getValue.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(HelloEditText.this, editText.getText().toString(), Toast.LENGTH_SHORT).show(); } }); //讓EditText全選 Button all=(Button)findViewById(R.id.btn_all); all.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { editText.selectAll(); } }); //從第2個字符開始選擇EditText文本 Button select=(Button)findViewById(R.id.btn_select); select.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Editable editable=editText.getText(); Selection.setSelection(editable, 1,editable.length()); } }); //獲取選中的文本 Button getSelect=(Button)findViewById(R.id.btn_get_select); getSelect.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int start=editText.getSelectionStart(); int end=editText.getSelectionEnd(); CharSequence selectText=editText.getText().subSequence(start, end); Toast.makeText(HelloEditText.this, selectText, Toast.LENGTH_SHORT).show(); } }); } /** * 交換兩個索引 * @param start 開始索引 * @param end 結束索引 */ protected void switchIndex(int start, int end) { int temp=start; start=end; end=temp; } }
自定義View控件解決android文字排版和換行的問題(轉,還沒有測試)
http://www.eoeandroid.com/thread-64055-1-1.html
import java.util.Vector; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.FontMetrics; import android.util.AttributeSet; import android.view.View; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.TextView; public class MyView extends TextView { private final String namespace="http://www.nearmobile.net"; private int resourceId=0; /* 聲明Paint對象 */ private Paint mPaint = null; /* 聲明TextUtil對象 */ private TextUtil mTextUtil = null; public static int m_iTextHeight; private WindowManager wm=null; private String string=""; public MyView(Context context, AttributeSet set) { super(context,set); resourceId=set.getAttributeResourceValue(namespace, "text", 0); if(resourceId==0) string=set.getAttributeValue(null,"text"); else string=this.getResources().getString(resourceId); wm=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE); /* 構建對象 */ m_iTextHeight=2000; mPaint = new Paint(); mPaint.setColor(Color.RED); mPaint.setStrokeWidth(40); mPaint.setTextSize(20); int m_iTextWidth=wm.getDefaultDisplay().getWidth(); FontMetrics fm = mPaint.getFontMetrics(); int m_iFontHeight = (int) Math.ceil(fm.descent - fm.top) + 4; 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+2)*m_iFontHeight+2; //用反射機制獲得 m_iTextHeight 值 /* 實例化TextUtil mTextUtil = new TextUtil(string,5,25,wm.getDefaultDisplay().getWidth(),this.getHeight(),0x0,0xffffff,255,15); 初始化TextUtil mTextUtil.InitText(string,5,25,wm.getDefaultDisplay().getWidth(),wm.getDefaultDisplay().getHeight(),0x0,0xffffff,255,15);*/ } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); /* 設置背景顏色 */ canvas.drawColor(Color.BLACK); mPaint.setAntiAlias(true); char ch; int w = 0; int istart = 0; int m_iFontHeight; int m_iRealLine=0; int x=2; int y=60; Vector m_String=new Vector(); int m_iTextWidth=wm.getDefaultDisplay().getWidth(); FontMetrics fm = mPaint.getFontMetrics(); m_iFontHeight = (int) Math.ceil(fm.descent - fm.top) + 4; //m_ipageLineNum = m_iTextHeight / m_iFontHeight; 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; System.out.println("m_iTextHeight----->"+m_iTextHeight); 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); this.setLayoutParams(new LinearLayout.LayoutParams(measuredWidth,measuredHeight)); 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. 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 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; } }
TextView 垂直自動滾動
http://www.cnblogs.com/vaiyanzi/archive/2011/12/06/2277791.html
在TextView中自定義連接
http://handroid.diandian.com/post/2011-09-11/4961075
實現TextView中文字連接的方式
http://aichixihongshi.iteye.com/blog/1197726
TextView 文本自動對齊
http://blog.csdn.net/hudan2714/article/details/7816692
帶清除功能的輸入框控件ClearEditText,仿IOS的輸入框
http://blog.csdn.net/xiaanming/article/details/11066685