android,java使用Button 可能都会监听之 当其被点击 就会有函数负责回调 那么其到底是怎么实现的呢?
今天要做的就是摸清楚之 为了减少不必要的麻烦 打算extends EditText 并在其上设立监听器
[代码 步骤]
1. 定义Edit2Text 且extends EditText
- public class Edit2Text extends EditText {
- OnTextChangedListener changedListener;
- TextWatcher tWatcher;
- }
复制代码
2. 定义其上的监听器:OnTextChangedListener 并定义函数:onChanged() 用于执行具体回调
- public static interface OnTextChangedListener {
- public void onChanged(Edit2Text e2t, String text);
- }
复制代码
- 需要注意的 这几行代码的修饰关键字:
- 1. static :使其能够脱离Edit2Text而存在
- 2. interface : 使其自动填充其内部函数
- 3. “void onChanged(Edit2Text e2t, String text)” 中的第一个参数e2t 用于做分别 具体奥妙 后面再细说
复制代码
3. 设定监听器
- public void setOnChangedListener(OnTextChangedListener l){
- changedListener = l;
- }
复制代码
4. 定义TextWatcher 当字符内容改变 通知监听器
* 定义TextWatcher'
- tWatcher = new TextWatcher(){
- @Override
- public void afterTextChanged(Editable s) {
- // TODO Auto-generated method stub
- 06.
- }
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count,
- int after) {
- // TODO Auto-generated method stub
-
- }
- @Override
- public void onTextChanged(CharSequence s, int start, int before,
- int count) {
- // TODO Auto-generated method stub
- updateText(s.toString());
- }
-
- };
-
- this.addTextChangedListener(tWatcher);
复制代码
* 通知监听器
- private void updateText(String s){
- changedListener.onChanged(this, s);
- }
复制代码
5. 如何使用
- public class Edit2TextTest extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- 06. setContentView(R.layout.main);
- Edit2Text e2t = new Edit2Text(this);
- setContentView(e2t);
-
- e2t.setOnChangedListener(new Edit2Text.OnTextChangedListener(){
- @Override
- public void onChanged(Edit2Text e2t, String text) {
- // TODO Auto-generated method stub
- Log.d("TAG","[String:]"+text);
- }
- });
- }
- }
复制代码
* Log 信息:
- Java代码 收藏代码
- 01. D/dalvikvm( 674): GC freed 223 objects / 8848 bytes in 108m
- 02. D/TAG ( 941): [String:]i am
- 03. D/TAG ( 941): [String:]i am
- 04. D/TAG ( 941): [String:]i am e
- 05. D/TAG ( 941): [String:]i am ed
- 06. D/TAG ( 941): [String:]i am edi
- 07. D/TAG ( 941): [String:]i am edit
- 08. D/TAG ( 941): [String:]i am edit2
- 09. D/TAG ( 941): [String:]i am edit2t
- 10. D/TAG ( 941): [String:]i am edit2te
- 11. D/TAG ( 941): [String:]i am edit2tex
- 12. D/TAG ( 941): [String:]i am edit2text
- 13. D/TAG ( 941): [String:]i am edit2text,
- 14. D/TAG ( 941): [String:]i am edit2text,
- 15. D/TAG ( 941): [String:]i am edit2text, h
- 16. D/TAG ( 941): [String:]i am edit2text, he
- 17. D/TAG ( 941): [String:]i am edit2text, hel
- 18. D/TAG ( 941): [String:]i am edit2text, hell
- 19. D/TAG ( 941): [String:]i am edit2text, hello
- 20. D/TAG ( 941): [String:]i am edit2text, hello!
|