Android EditText部分特殊功能

本文介绍EditText组件的多种高级使用技巧,包括实现文字选中效果、防止自动获取焦点、字数限制及提示,以及禁用输入功能等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 http://06peng.com/tb.php?t=79&extra=456de

1、给EditText加上文字选中功能,比如微博的插入话题功能。点击“插入话题”按钮的时候,“#请插入话题名称#”在两个#号中间的内容处于选中状态,用户一点击即消失。代码如下:

Java代码
  1.     
  2. text.setText("#请插入话题名称#");       
  3. Editable editable = text.getText();       
  4. Selection.setSelection(editable, 1, editable.length() - 1);  

2、如果想默认进入一个Activity时,唯一的一个edittext先不要获得焦点。在EditText前面加上一个没有大小的Layout:

XML/HTML代码
  1.     
  2. <LinearLayout       
  3.     android:focusable="true" android:focusableInTouchMode="true"       
  4.     android:layout_width="0px" android:layout_height="0px"/>  

3、输入文字的时候,如果想限制字数,并提示用户,可用以下方法:

Java代码
  1.     
  2. text.addTextChangedListener(new TextWatcher() {       
  3.                    
  4.             @Override       
  5.             public void onTextChanged(CharSequence s, int start, int before, int count) {       
  6.                  textCount = textCount + count - before;       
  7.                  if (textCount <= 140) {       
  8.                        writeWordDes.setText("可输入字数:" + (140 - textCount));       
  9.                        writeWordDes.setTextColor(getResources().getColor(R.color.solid_black));       
  10.                  } else {       
  11.                      writeWordDes.setText("超出字数:" + (textCount - 140));       
  12.                      writeWordDes.setTextColor(getResources().getColor(R.color.solid_red));       
  13.                  }       
  14.             }       
  15.                    
  16.             @Override       
  17.             public void beforeTextChanged(CharSequence s, int start, int count,       
  18.                     int after) {       
  19.                        
  20.             }       
  21.                    
  22.             @Override       
  23.             public void afterTextChanged(Editable s) {       
  24.                        
  25.             }       
  26.         });       
  27.     }  

4、让EditText不可输入,比如超过一定字数后,不让用户再输入文字:

Java代码
  1.     
  2. text.setFilters(new InputFilter[] {         
  3.          new InputFilter() {         
  4.                 public CharSequence filter(CharSequence source, int start,         
  5.                         int end, Spanned dest, int dstart, int dend) {         
  6.                     return source.length() < 1 ? dest.subSequence(dstart, dend) : "";         
  7.                 }         
  8.             }         
  9.         });    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值