对 EditText 控件的监听

本文介绍了一个在Android应用中实现文本输入实时更新到UI组件的实用技巧,通过使用EditText的TextWatcher接口来监测文本变化并相应地更新TextView。此方法适用于需要即时反馈用户输入场景的应用开发。

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

public class MainActivity extends Activity {
 private TextView textView=null;
 private EditText editText=null;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  textView=(TextView)findViewById(R.id.textView);
  editText=(EditText)findViewById(R.id.editText);
  editText.addTextChangedListener(new TextWatcher() {
   @Override
   public void onTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub
    String text=editText.getText().toString();
    textView.setText(text);
    /**
     * 增加数据时before=0删除数据时before=1
     * count记录每次输入文本框中的字符数
     * s表示文本框中当前的字符串
     * start记录从什么位置开始,以0为起点
     */
   }
   @Override
   public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    // TODO Auto-generated method stub
    /**
     * 当从文本框中删除数据时after=0增加数据时after=1
     * s表示文本框中当前的字符串
     * count记录每次输入文本框中的字符数
     * start从零开始计数,统计文本框中有多少字符
     */
   }
   @Override
   public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
   }
  });
 }
}

 

onTextChanged方法:当文本框中的信息改变时执行

beforeTextChanged方法:在文本框中的信息改变以前执行

afterTextChanged方法:在文本框中的信息改变之后执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值