使用TextView/EditText應該注意的地方

Android字體陰影
strings.xml文件定義字符串中的標籤
Android TextView 自動換行問題

關於android軟鍵盤enter鍵的替換與事件監聽
軟件盤的界面替換隻有一個屬性android:imeOptions,這個屬性的可以取的值有normal,actionUnspecified,actionNone,actionGo,actionSearch,actionSend,actionNext,actionDone,例如當值爲actionNext時enter鍵外觀變成一個向下箭頭,而值爲actionDone時enter鍵外觀則變成了“完成”兩個字。
我們也可以重寫enter的事件,方法如下:
Java代碼 複製代碼 收藏代碼
  1. TextView editText = new TextView(this);   
  2. editText.setOnEditorActionListene(   
  3. newTextView.OnEditorActionListener() {      
  4.           public boolean onEditorAction(TextView v, int actionId,      
  5.                             KeyEvent event){      
  6.                         if (actionId == EditorInfo.IME_ACTION_SEND)      
  7.                         {      
  8.                             // 在這裏編寫自己想要實現的功能      
  9.                         }      
  10.                         return false;      
  11.           }      
  12. });   
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自帶的軟鍵盤,該軟鍵盤會佔用整個界面,那麼,如何讓鍵盤只佔用屏幕的一部分呢?
Xml代碼 複製代碼 收藏代碼
  1. <EditText    
  2.     android:id="@+id/text1"    
  3.     android:layout_width="150dip"    
  4.     android:layout_height="wrap_content"  
  5.     android:imeOptions="flagNoExtractUi"/>  

使用android:imeOptinos可對Android自帶的軟鍵盤進行一些界面上的設置:
Xml代碼 複製代碼 收藏代碼
  1. android:imeOptions="flagNoExtractUi"  //使軟鍵盤不全屏顯示,只佔用一部分屏幕   
  2. 同時,這個屬性還能控件軟鍵盤右下角按鍵的顯示內容,默認情況下爲回車鍵   
  3. android:imeOptions="actionNone"  //輸入框右側不帶任何提示   
  4. android:imeOptions="actionGo"    //右下角按鍵內容爲'開始'   
  5. android:imeOptions="actionSearch"  //右下角按鍵爲放大鏡圖片,搜索   
  6. android:imeOptions="actionSend"    //右下角按鍵內容爲'發送'   
  7. android:imeOptions="actionNext"   //右下角按鍵內容爲'下一步'   
  8. android:imeOptions="actionDone"  //右下角按鍵內容爲'完成'   

同時,可能EditText添加相應的監聽器,捕捉用戶點擊了軟鍵盤右下角按鈕的監聽事件,以便進行處理。
Java代碼 複製代碼 收藏代碼
  1. editText.setOnEditorActionListener(new OnEditorActionListener() {   
  2.         @Override  
  3.         public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {   
  4.             Toast.makeText(MainActivity.this"text2", Toast.LENGTH_SHORT).show();   
  5.             return false;   
  6.         }   
  7.     });  
 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
Xml代碼 複製代碼 收藏代碼
  1. <style name="AudioFileInfoOverlayText">    
  2.     <item name="android:paddingLeft">4px</item>    
  3.     <item name="android:paddingBottom">4px</item>    
  4.     <item name="android:textColor">#ffffffff</item>    
  5.     <item name="android:textSize">12sp</item>    
  6.     <item name="android:shadowColor">#ff00ff00</item>    
  7.     <item name="android:shadowDx">5</item>    
  8.     <item name="android:shadowDy">3</item>    
  9.     <item name="android:shadowRadius">6</item>  
  10. </style>  
  11.   
  12. <TextView android:id="@+id/info"    
  13.        android:layout_width="fill_parent"    
  14.        android:layout_height="wrap_content"    
  15.        style="@style/AudioFileInfoOverlayText"    
  16.        android:text="aaaa"    
  17.        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
Xml代碼 複製代碼 收藏代碼
  1. <TextView android:id="@+id/tv"  
  2.         android:layout_width="fill_parent"  
  3.         android:layout_height="wrap_content"  
  4.         android:textColor="#FF00FF00"  
  5.         android:textSize="20px"  
  6.         android:lines="4"  
  7.         android:ellipsize="end"  
  8.         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"  
  9.         />  

不要將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輸入字數做限制?
Java代碼 複製代碼 收藏代碼
  1. private EditText mEditText ;   
  2.         mEditText  = (EditText) findViewById(R.id.mEditText );   
  3. /** 限制字數 */  
  4.         mEditText  .addTextChangedListener(new TextWatcher() {   
  5.             private CharSequence temp;                 
  6.             private int selectionStart ;                 
  7.             private int selectionEnd ;   
  8.             @Override  
  9.             public void beforeTextChanged(CharSequence s, int start, int count,   
  10.                     int after) {   
  11.                 temp = s;    
  12.             }   
  13.                
  14.             @Override  
  15.             public void onTextChanged(CharSequence s, int start, int before,   
  16.                     int count) {   
  17.                    
  18.             }    
  19.                
  20.             @Override  
  21.             public void afterTextChanged(Editable s) {   
  22.                 selectionStart = mEditText  .getSelectionStart();                     
  23.                 selectionEnd = mEditText  .getSelectionEnd();                     
  24.                 Log.d(TAG,""+selectionStart);                     
  25.                 if (temp.length() > 8) {                         
  26.                     Toast.makeText(MAUpdateAty.this"字數不能超過8個", Toast.LENGTH_SHORT).show();                         
  27.                     s.delete(selectionStart-1, selectionEnd);                         
  28.                     int tempSelection = selectionStart;                         
  29.                     mEditText  .setText(s);                         
  30.                     mEditText  .setSelection(tempSelection);                     
  31.                 }    
  32.                 Log.d(TAG," "+selectionEnd);   
  33.             }   
  34.         });  
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);
            }
        });

或者試試這個:
Java代碼 複製代碼 收藏代碼
  1. private TextWatcher mTextWatcher = new TextWatcher(){   
  2.   Toast mToast = null;   
  3.   public void beforeTextChanged(CharSequence s, int start,    
  4.     int count,int after) {   
  5.   }   
  6.   
  7.   public void onTextChanged(CharSequence s, int start,    
  8.     int before,int count) {   
  9.   }   
  10.      
  11.   public void afterTextChanged(Editable s) {   
  12.    int nSelStart = 0;   
  13.    int nSelEnd = 0;   
  14.    boolean nOverMaxLength = false;   
  15.       
  16.    nSelStart = mEditText.getSelectionStart();   
  17.    nSelEnd   = mEditText.getSelectionEnd();   
  18.       
  19.    nOverMaxLength = (s.length() > Constants.MAX_TEXT_INPUT_LENGTH) ? true : false;   
  20.    if(nOverMaxLength){   
  21.     if(null == mToast){   
  22.      mToast = Toast.makeText(mContext,    
  23.        R.string.IDS_MSG_TEXT_OVER_MAXLENGTH,    
  24.        Toast.LENGTH_SHORT);   
  25.     }   
  26.     mToast.show();   
  27.        
  28.     s.delete(nSelStart - 1, nSelEnd);   
  29.   
  30.     mEditText.setTextKeepState(s);//請讀者注意這一行,保持光標原先的位置,而 mEditText.setText(s)會讓光標跑到最前面,就算是再加mEditText.setSelection(nSelStart) 也不起作用   
  31.     }   
  32.   }   
  33.  };  
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來設置輸入的最大長度

控制輸入小數的位數
Java代碼 複製代碼 收藏代碼
  1. // 設置小數位數控制   
  2.         InputFilter lengthfilter = new InputFilter() {   
  3.             public CharSequence filter(CharSequence source, int start, int end,   
  4.                     Spanned dest, int dstart, int dend) {   
  5.                 // 刪除等特殊字符,直接返回   
  6.                 if ("".equals(source.toString())) {   
  7.                     return null;   
  8.                 }   
  9.                 String dValue = dest.toString();   
  10.                 String[] splitArray = dValue.split("\\.");   
  11.                 if (splitArray.length > 1) {   
  12.                     String dotValue = splitArray[1];   
  13.                     int diff = dotValue.length() + 1 - digLength;   
  14.                     if (diff > 0) {   
  15.                         return source.subSequence(start, end - diff);   
  16.                     }   
  17.                 }   
  18.                 return null;   
  19.             }   
  20.         };   
  21.         inputEdit.setFilters(new InputFilter[] { lengthfilter });  
// 設置小數位數控制
		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 獲得輸入的焦點,那麼可以使用下面的語句,
Java代碼 複製代碼 收藏代碼
  1. getCurrentFocus().setFocusable(false);   
  2. getCurrentFocus().setFocusableInTouchMode(false);  
getCurrentFocus().setFocusable(false);
getCurrentFocus().setFocusableInTouchMode(false);

而要獲得焦點的 EditText :
Java代碼 複製代碼 收藏代碼
  1. mSearchEdit.setFocusable(true);   
  2. mSearchEdit.setFocusableInTouchMode(true);   
  3. mSearchEdit.requestFocus();  
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中輸入進行
對比,輸入錯誤,則用“×”替換所輸入的字符。
Java代碼 複製代碼 收藏代碼
  1. import android.app.Activity;   
  2. import android.os.Bundle;   
  3. import android.text.InputFilter;   
  4. import android.text.Spanned;   
  5. import android.util.Log;   
  6. import android.widget.EditText;   
  7. import android.widget.TextView;   
  8. import android.widget.Toast;   
  9.   
  10. public class MyFilterTest extends Activity {   
  11.     /** Called when the activity is first created. */  
  12.     TextView myText;   
  13.     EditText myEdit;   
  14.     @Override  
  15.     public void onCreate(Bundle savedInstanceState) {   
  16.         super.onCreate(savedInstanceState);   
  17.         setContentView(R.layout.main);   
  18.         final String str = "Hello,Android!";   
  19.            
  20.         myText=(TextView)findViewById(R.id.myText);   
  21.         myText.setText(str);   
  22.         myEdit=(EditText)findViewById(R.id.myEdit);   
  23.            
  24.         myEdit.setFilters(new InputFilter[]{ new MyInputFilter(str) });   
  25.            
  26.     }   
  27.     public class MyInputFilter implements InputFilter{   
  28.         String str=null;   
  29.         public MyInputFilter(String str){   
  30.             this.str=str;   
  31.         }   
  32.         @Override  
  33.         public CharSequence filter(CharSequence src, int start, int end,   
  34.                 Spanned dest, int dstart, int dend) {   
  35.             // TODO Auto-generated method stub   
  36.             String ch=null;   
  37.             String TAG="Filter";   
  38.             Log.w(TAG,"src:"+src+";start:"+start+";end:"+end);   
  39.             Log.w(TAG,"dest:"+dest+";dstart:"+dstart+";dend:"+dend);   
  40.             if(dest.length()<str.length()){   
  41.                 ch=str.substring(dstart+start, dstart+end);   
  42.             }else{   
  43.                 return dest.subSequence(dstart, dend);   
  44.             }   
  45.                    
  46.             if(ch.equals(src)){   
  47.                
  48.                 Toast.makeText(MyFilterTest.this"match", Toast.LENGTH_SHORT).show();   
  49.                 return dest.subSequence(dstart, dend)+src.toString();   
  50.             }else{   
  51.                 Toast.makeText(MyFilterTest.this"mismatch", Toast.LENGTH_SHORT).show();   
  52.                 return dest.subSequence(dstart, dend)+"×";   
  53.             }   
  54.         }                  
  55.     }   
  56. }  
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隱藏鍵盤 ?
Java代碼 複製代碼 收藏代碼
  1. (EditText)mMarket.setInputType(0);  
(EditText)mMarket.setInputType(0);


如何設置EditText不被輸入法遮蓋 ?
Java代碼 複製代碼 收藏代碼
  1. getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);  
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

如何解決軟鍵盤彈出引起的各種不適


如何隱藏Activity剛進來焦點在EditText時顯示輸入鍵盤?
一個Activity剛進來時焦點在EditText時,會彈出輸入的鍵盤,這不是我想要的,然後就想辦法隱藏掉輸入鍵盤。嘗試了EditText的clearFocus不行,也試過其它控件ruquestFocus也不行,用隱藏鍵盤的方法http://mingkg21.iteye.com/blog/548642
不行。試試下面這種:
Java代碼 複製代碼 收藏代碼
  1. getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);  
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顯示或隱藏密碼
Java代碼 複製代碼 收藏代碼
  1. if (isChecked) {   
  2.             System.out.println("checked");   
  3.             // 顯示密碼   
  4.             password_edit.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);    
  5.         } else {   
  6.             System.out.println("not checked");   
  7.             // 隱藏密碼   
  8.             password_edit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);   
  9.         }  
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小寫轉大寫
Java代碼 複製代碼 收藏代碼
  1. final EditText input = new EditText(this);   
  2. InputFilter[] FilterArray = new InputFilter[1];   
  3. FilterArray[0] = new InputFilter.AllCaps();   
  4. input.setFilters(FilterArray);  
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
Xml代碼 複製代碼 收藏代碼
  1. <!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->  
  2. <!--最簡單的方法是在TextView的父容器(通常是LinearLayout)中設置android:focusable="true" android:focusableInTouchMode="true",這樣就把焦點從EditText上移走了。-->  
  3. <LinearLayout  
  4.     android:focusable="true" android:focusableInTouchMode="true"  
  5.     android:layout_width="0px" android:layout_height="0px">  
  6. <!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component   
  7.      to prevent the dummy from receiving focus again -->  
  8.     <AutoCompleteTextView android:id="@+id/text"  
  9.         android:layout_width="fill_parent" android:layout_height="wrap_content"  
  10.         android:nextFocusUp="@+id/text" android:nextFocusLeft="@+id/text"/>  
  11. </LinearLayout>  


徹底隱藏軟鍵盤
Java代碼 複製代碼 收藏代碼
  1. EditText et=(EditText)findViewById(R.id.edit);   
  2. et.setInputType(InputType.TYPE_DATETIME_VARIATION_NORMAL);  
EditText et=(EditText)findViewById(R.id.edit);
et.setInputType(InputType.TYPE_DATETIME_VARIATION_NORMAL);


tv.setCompoundDrawables()不起作用?
Java代碼 複製代碼 收藏代碼
  1. Drawable leftDrawable;   
  2. leftDrawable= getResources().getDrawable(R.drawable.left_drawable);   
  3. // user setCompoundDrawables()  method , you must call Drawable.setBounds()  method !Or  the Image can't show .   
  4. leftDrawable.setBounds(00, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight());   
  5. mTextView.setCompoundDrawables(leftDrawable, nullnullnull);   
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來改變默認的“完成”文本。這裏舉幾個常用的常量值:

Xml代碼 複製代碼 收藏代碼
  1. <EditText     
  2.     android:id="@+id/edit_text"       
  3.     android:layout_width="fill_parent"      
  4.     android:layout_height="wrap_content"     
  5.     android:imeOptions="actionSearch"/>  


EditText的取值、全選、部分選擇、獲取選中文本
       下面通過一個例子來演示EditText的取值、全選、部分選擇和獲取選中文本.main.xml如下:
Xml代碼 複製代碼 收藏代碼
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7. <EditText  
  8.     android:id="@+id/edit_text"     
  9.     android:layout_width="fill_parent"    
  10.     android:layout_height="wrap_content"  
  11.     android:imeOptions="actionSearch"/>  
  12. <Button    
  13.     android:id="@+id/btn_get_value"  
  14.     android:text="取值"  
  15.     android:layout_width="wrap_content"  
  16.     android:layout_height="wrap_content"/>  
  17. <Button    
  18.     android:id="@+id/btn_all"  
  19.     android:text="全選"  
  20.     android:layout_width="wrap_content"  
  21.     android:layout_height="wrap_content"/>  
  22. <Button    
  23.     android:id="@+id/btn_select"  
  24.     android:text="從第2個字符開始選擇"  
  25.     android:layout_width="wrap_content"  
  26.     android:layout_height="wrap_content"/>  
  27. <Button    
  28.     android:id="@+id/btn_get_select"  
  29.     android:text="獲取選中文本"  
  30.     android:layout_width="wrap_content"  
  31.     android:layout_height="wrap_content"/>  
  32. </LinearLayout>  

代碼:
Java代碼 複製代碼 收藏代碼
  1. package com.flysnow;   
  2.   
  3. import android.app.Activity;   
  4. import android.os.Bundle;   
  5. import android.text.Editable;   
  6. import android.text.Selection;   
  7. import android.view.KeyEvent;   
  8. import android.view.View;   
  9. import android.view.View.OnClickListener;   
  10. import android.widget.Button;   
  11. import android.widget.EditText;   
  12. import android.widget.TextView;   
  13. import android.widget.Toast;   
  14. import android.widget.TextView.OnEditorActionListener;   
  15. /**  
  16.  * EditText演示  
  17.  * @author 飛雪無情  
  18.  * @since 2010-11-29  
  19.  */  
  20. public class HelloEditText extends Activity {   
  21.     /** Called when the activity is first created. */  
  22.     @Override  
  23.     public void onCreate(Bundle savedInstanceState) {   
  24.         super.onCreate(savedInstanceState);   
  25.         setContentView(R.layout.main);   
  26.         final EditText editText=(EditText)findViewById(R.id.edit_text);   
  27.         //監聽回車鍵   
  28.         editText.setOnEditorActionListener(new OnEditorActionListener() {   
  29.             @Override  
  30.             public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {   
  31.                 Toast.makeText(HelloEditText.this, String.valueOf(actionId), Toast.LENGTH_SHORT).show();   
  32.                 return false;   
  33.             }   
  34.         });   
  35.         //獲取EditText文本   
  36.         Button getValue=(Button)findViewById(R.id.btn_get_value);   
  37.         getValue.setOnClickListener(new OnClickListener() {   
  38.             @Override  
  39.             public void onClick(View v) {   
  40.                 Toast.makeText(HelloEditText.this, editText.getText().toString(), Toast.LENGTH_SHORT).show();   
  41.             }   
  42.         });   
  43.         //讓EditText全選   
  44.         Button all=(Button)findViewById(R.id.btn_all);   
  45.         all.setOnClickListener(new OnClickListener() {   
  46.             @Override  
  47.             public void onClick(View v) {   
  48.                 editText.selectAll();   
  49.             }   
  50.         });   
  51.         //從第2個字符開始選擇EditText文本   
  52.         Button select=(Button)findViewById(R.id.btn_select);   
  53.         select.setOnClickListener(new OnClickListener() {   
  54.             @Override  
  55.             public void onClick(View v) {   
  56.                 Editable editable=editText.getText();   
  57.                 Selection.setSelection(editable, 1,editable.length());   
  58.             }   
  59.         });   
  60.       //獲取選中的文本   
  61.         Button getSelect=(Button)findViewById(R.id.btn_get_select);   
  62.         getSelect.setOnClickListener(new OnClickListener() {   
  63.             @Override  
  64.             public void onClick(View v) {   
  65.                 int start=editText.getSelectionStart();   
  66.                 int end=editText.getSelectionEnd();   
  67.                 CharSequence selectText=editText.getText().subSequence(start, end);   
  68.                 Toast.makeText(HelloEditText.this, selectText, Toast.LENGTH_SHORT).show();   
  69.             }   
  70.         });   
  71.     }   
  72.     /**  
  73.      * 交換兩個索引  
  74.      * @param start 開始索引  
  75.      * @param end 結束索引  
  76.      */  
  77.     protected void switchIndex(int start, int end) {   
  78.         int temp=start;   
  79.         start=end;   
  80.         end=temp;   
  81.     }   
  82. }  
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
Java代碼 複製代碼 收藏代碼
  1. import java.util.Vector;   
  2. import android.content.Context;   
  3. import android.graphics.Canvas;   
  4. import android.graphics.Color;   
  5. import android.graphics.Paint;   
  6. import android.graphics.Paint.FontMetrics;   
  7. import android.util.AttributeSet;   
  8. import android.view.View;   
  9. import android.view.WindowManager;   
  10. import android.widget.LinearLayout;   
  11. import android.widget.TextView;   
  12. public class MyView extends TextView {   
  13. private final String namespace="http://www.nearmobile.net";   
  14.   
  15. private int resourceId=0;   
  16.   
  17.   
  18. /* 聲明Paint對象 */  
  19. private Paint mPaint = null;   
  20. /* 聲明TextUtil對象 */  
  21. private TextUtil mTextUtil = null;   
  22.   
  23. public  static  int m_iTextHeight;   
  24. private WindowManager wm=null;   
  25. private String string="";   
  26.     public MyView(Context context, AttributeSet set) {   
  27.         super(context,set);   
  28.            
  29.         resourceId=set.getAttributeResourceValue(namespace, "text"0);   
  30.            
  31.          if(resourceId==0)   
  32.           string=set.getAttributeValue(null,"text");   
  33.          else  
  34.           string=this.getResources().getString(resourceId);   
  35.      
  36.         wm=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE);   
  37.         /* 構建對象 */  
  38.         m_iTextHeight=2000;   
  39.   mPaint = new Paint();   
  40.   mPaint.setColor(Color.RED);   
  41.   mPaint.setStrokeWidth(40);   
  42.   mPaint.setTextSize(20);   
  43.      
  44.      
  45.   int m_iTextWidth=wm.getDefaultDisplay().getWidth();   
  46.   FontMetrics fm = mPaint.getFontMetrics();   
  47.      
  48.   int m_iFontHeight = (int) Math.ceil(fm.descent - fm.top) + 4;   
  49.   int line=0;   
  50.   int istart=0;   
  51.   int w=0;   
  52.   for (int i = 0; i < string.length(); i++)   
  53.   {   
  54.    char ch = string.charAt(i);   
  55.    float[] widths = new float[1];   
  56.    String srt = String.valueOf(ch);   
  57.    mPaint.getTextWidths(srt, widths);   
  58.    if (ch == '\n')   
  59.    {   
  60.     line++;   
  61.     istart = i + 1;   
  62.     w = 0;   
  63.    }   
  64.    else  
  65.    {   
  66.     w += (int) (Math.ceil(widths[0]));   
  67.     if (w > m_iTextWidth)   
  68.     {   
  69.      line++;   
  70.      istart = i;   
  71.      i--;   
  72.      w = 0;   
  73.     }   
  74.     else  
  75.     {   
  76.      if (i == (string.length() - 1))   
  77.      {   
  78.       line++;   
  79.      }   
  80.     }   
  81.    }   
  82.   }   
  83.   m_iTextHeight=(line+2)*m_iFontHeight+2;   
  84.   //用反射機制得到     m_iTextHeight  值   
  85.   
  86.      
  87. /*  實例化TextUtil   
  88.   mTextUtil = new TextUtil(string,5,25,wm.getDefaultDisplay().getWidth(),this.getHeight(),0x0,0xffffff,255,15);  
  89.     
  90.    初始化TextUtil   
  91.   mTextUtil.InitText(string,5,25,wm.getDefaultDisplay().getWidth(),wm.getDefaultDisplay().getHeight(),0x0,0xffffff,255,15);*/  
  92.     }   
  93.         
  94.        
  95.        
  96.        
  97.     @Override  
  98.     protected void onDraw(Canvas canvas) {   
  99.           
  100.        super.onDraw(canvas);   
  101.        /* 設置背景顏色 */  
  102.     canvas.drawColor(Color.BLACK);   
  103.        
  104.     mPaint.setAntiAlias(true);   
  105.      
  106.      char ch;   
  107.   int w = 0;   
  108.   int istart = 0;   
  109.   int m_iFontHeight;   
  110.   int m_iRealLine=0;   
  111.   int x=2;   
  112.   int y=60;   
  113.   Vector m_String=new Vector();   
  114.   int m_iTextWidth=wm.getDefaultDisplay().getWidth();   
  115.   FontMetrics fm = mPaint.getFontMetrics();   
  116.      
  117.   m_iFontHeight = (int) Math.ceil(fm.descent - fm.top) + 4;   
  118.   //m_ipageLineNum = m_iTextHeight / m_iFontHeight;   
  119.   for (int i = 0; i < string.length(); i++)   
  120.   {   
  121.    ch = string.charAt(i);   
  122.    float[] widths = new float[1];   
  123.    String srt = String.valueOf(ch);   
  124.    mPaint.getTextWidths(srt, widths);   
  125.    if (ch == '\n')   
  126.    {   
  127.     m_iRealLine++;   
  128.     m_String.addElement(string.substring(istart, i));   
  129.     istart = i + 1;   
  130.     w = 0;   
  131.    }   
  132.    else  
  133.    {   
  134.     w += (int) (Math.ceil(widths[0]));   
  135.     if (w > m_iTextWidth)   
  136.     {   
  137.      m_iRealLine++;   
  138.      m_String.addElement(string.substring(istart, i));   
  139.      istart = i;   
  140.      i--;   
  141.      w = 0;   
  142.     }   
  143.     else  
  144.     {   
  145.      if (i == (string.length() - 1))   
  146.      {   
  147.       m_iRealLine++;   
  148.       m_String.addElement(string.substring(istart, string.length()));   
  149.      }   
  150.     }   
  151.    }   
  152.   }   
  153.   m_iTextHeight=m_iRealLine*m_iFontHeight+2;   
  154.   System.out.println("m_iTextHeight----->"+m_iTextHeight);   
  155.   canvas.setViewport(m_iTextWidth, m_iTextWidth);   
  156.   for (int i = 0, j = 0; i < m_iRealLine; i++, j++)   
  157.   {   
  158.    canvas.drawText((String) (m_String.elementAt(i)), x,  y+m_iFontHeight * j, mPaint);   
  159.   }   
  160.     }     
  161.       
  162.        
  163.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {     
  164.         
  165.      int measuredHeight = measureHeight(heightMeasureSpec);     
  166.           
  167.      int measuredWidth = measureWidth(widthMeasureSpec);     
  168.           
  169.       this.setMeasuredDimension(measuredWidth, measuredHeight);   
  170.        this.setLayoutParams(new LinearLayout.LayoutParams(measuredWidth,measuredHeight));   
  171.        super.onMeasure(widthMeasureSpec, heightMeasureSpec);   
  172.      }     
  173.           
  174.            
  175.           
  176.      private int measureHeight(int measureSpec) {     
  177.           
  178.      int specMode = MeasureSpec.getMode(measureSpec);     
  179.           
  180.      int specSize = MeasureSpec.getSize(measureSpec);     
  181.           
  182.            
  183.           
  184.      // Default size if no limits are specified.     
  185.           
  186.      int result = m_iTextHeight;     
  187.           
  188.      if (specMode == MeasureSpec.AT_MOST)      
  189.           
  190.      {     
  191.           
  192.      // Calculate the ideal size of your     
  193.           
  194.      // control within this maximum size.     
  195.           
  196.      // If your control fills the available     
  197.           
  198.      // space return the outer bound.     
  199.           
  200.      result = specSize;     
  201.           
  202.      }      
  203.           
  204.      else if (specMode == MeasureSpec.EXACTLY)      
  205.           
  206.      {     
  207.           
  208.      // If your control can fit within these bounds return that value.     
  209.           
  210.      result = specSize;     
  211.           
  212.      }     
  213.           
  214.      return result;     
  215.           
  216.      }     
  217.           
  218.            
  219.           
  220.      private int measureWidth(int measureSpec) {     
  221.           
  222.      int specMode = MeasureSpec.getMode(measureSpec);     
  223.           
  224.      int specSize = MeasureSpec.getSize(measureSpec);     
  225.           
  226.            
  227.           
  228.      // Default size if no limits are specified.     
  229.           
  230.      int result = 500;     
  231.           
  232.      if (specMode == MeasureSpec.AT_MOST)     
  233.          
  234.      {     
  235.           
  236.      // Calculate the ideal size of your control     
  237.           
  238.      // within this maximum size.      
  239.           
  240.      // If your control fills the available space     
  241.           
  242.      // return the outer bound.     
  243.           
  244.      result = specSize;     
  245.          
  246.      }      
  247.           
  248.      else if (specMode == MeasureSpec.EXACTLY)      
  249.           
  250.      {     
  251.           
  252.      // If your control can fit within these bounds return that value.     
  253.           
  254.      result = specSize;     
  255.           
  256.      }     
  257.           
  258.      return result;     
  259.           
  260.      }   
  261. }  
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
發佈了14 篇原創文章 · 獲贊 0 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章