What's the right way to extend EditText to give it additional “default” functionality

后端 未结 1 1794
隐瞒了意图╮
隐瞒了意图╮ 2021-02-08 09:33

I\'m wondering if it\'s possible to add functionality to EditText such that when I include my newly extended field in the layout xml, I don\'t have to then add any code to the A

相关标签:
1条回答
  • 2021-02-08 10:20

    Actually there is nothing complicated about that. Usually you would apply a InputFilter to your EditText in your code and this would do the job. But if you see a pattern in that and want a EditText which always behaves that way you could create a custom widget that way:

    public class PhoneEditText extends EditText {
    
        public PhoneEditText(Context context) {
            super(context);
            init();
        }
    
        public PhoneEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public PhoneEditText(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }
    
        private void init() {
                // set your input filter here
        }
    }
    

    In XML layout you would simply use the full path to your custom class instead EditText:

    <my.package.path.to.PhoneEditText
       attribute="value (all EditText attributes will work as they did before)" />
    
    0 讨论(0)
提交回复
热议问题