使用TextView/EditText应该注意的地方
Android TextView 自动换行问题
关于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; } }); <EditText android:id="@+id/text1" android:layout_width="150dip" android:layout_height="wrap_content" android:imeOptions="flagNoExtractUi"/>
android:imeOptions="flagNoExtractUi" //使软键盘不全屏显示,只占用一部分屏幕同时,这个属性还能控件软键盘右下角按键的显示内容,默认情况下为回车键android:imeOptions="actionNone" //输入框右侧不带任何提示android:imeOptions="actionGo" //右下角按键内容为'开始'android:imeOptions="actionSearch" //右下角按键为放大镜图片,搜索android:imeOptions="actionSend" //右下角按键内容为'发送'android:imeOptions="actionNext" //右下角按键内容为'下一步'android:imeOptions="actionDone" //右下角按键内容为'完成'
editText.setOnEditorActionListener(new OnEditorActionListener() {@Overridepublic boolean onEditorAction(TextView v, int actionId, KeyEvent event) {Toast.makeText(MainActivity.this, "text2", Toast.LENGTH_SHORT).show();return false;}});<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 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"/>
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 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 });getCurrentFocus().setFocusable(false);getCurrentFocus().setFocusableInTouchMode(false);
mSearchEdit.setFocusable(true);mSearchEdit.setFocusableInTouchMode(true);mSearchEdit.requestFocus();
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; }@Overridepublic CharSequence filter(CharSequence src, int start, int end,Spanned dest, int dstart, int dend) {// TODO Auto-generated method stubString 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)+"×";}} }}(EditText)mMarket.setInputType(0);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
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);}final EditText input = new EditText(this);InputFilter[] FilterArray = new InputFilter[1];FilterArray[0] = new InputFilter.AllCaps();input.setFilters(FilterArray);
<!-- 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);
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);

<EditText android:id="@+id/edit_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:imeOptions="actionSearch"/>
<?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" ><EditTextandroid: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() {@Overridepublic 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() {@Overridepublic 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() {@Overridepublic void onClick(View v) {editText.selectAll();}}); //从第2个字符开始选择EditText文本 Button select=(Button)findViewById(R.id.btn_select); select.setOnClickListener(new OnClickListener() {@Overridepublic 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() {@Overridepublic 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;}}
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; }}