http://blog.csdn.net/huichengongzi/article/details/7818676
监听 EditText 控件:
addTextChangedListener(new TextWatcher() { private CharSequence temp; private int selectionStart ; //监听光标位置 private int selectionEnd ; @Override public void onTextChanged(CharSequence s, int start, int before, int count) { temp = s.toString().trim(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { selectionStart = orderCountText.getSelectionStart(); selectionEnd = orderCountText.getSelectionEnd(); int tempcount = Integer.valueOf(temp.toString()); s.delete(selectionStart - 1, selectionEnd); int tempSelection = selectionStart; orderCountText.setText(s); orderCountText.setSelection(tempSelection); } });
关于android软键盘enter键的替换与事件监听
软件盘的界面替换只有一个属性android:imeOptions,这个属性的可以取的值有normal,actionUnspecified,actionNone,actionGo,actionSearch,actionSend,actionNext,actionDone,例如当值为actionNext时enter键外观变成一个向下箭头,而值为actionDone时enter键外观则变成了“完成”两个字。
我们也可以重写enter的事件,方法如下:
- 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自带的软键盘,该软键盘会占用整个界面,那么,如何让键盘只占用屏幕的一部分呢?
- <EditText
- android:id="@+id/text1"
- android:layout_width="150dip"
- android:layout_height="wrap_content"
- android:imeOptions="flagNoExtractUi"/>
使用android:imeOptinos可对Android自带的软键盘进行一些界面上的设置:
- 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
- <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行!
如何对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 == ' ')
- {
- 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 == ' ')
- {
- 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中文字链接的方式