什么是正确的方式来扩展的EditText给它附加的QUOT;默认"功能 [英] What's the right way to extend EditText to give it additional "default" functionality

查看:94
本文介绍了什么是正确的方式来扩展的EditText给它附加的QUOT;默认"功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有可能将功能添加到EditText上,这样当我包括我在布局XML新扩展的领域,我不必再添加任何code到活动类来得到它表现在具体方式。

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 Activity class to get it to behave in specific ways.

例如,我想提出一个EditPhone字段,它仅仅是一个拥有的监听关键事件,并修改该字段包括括号和破折号在其相应位置的附加功能一个EditText。

For example, I'd like to make a EditPhone field which is just an EditText that has the added feature of listening for key events and modifying the field to include parenthesis and dashes in their appropriate locations.

目前,我总是有包括监听code和其附加到视图,手动。但很明显的类有一吨的被包裹在它的默认行为(例如,它带来了,当你点击它的键盘)。所以,我猜它不应该是所有的艰难,但我不清楚什么步骤将是实现这一目标。

At the moment, I'm always having to include the listener code and attach it to the view, manually. But obviously the class has a ton of default behavior that is wrapped up in it (for example, it brings up the keyboard when you click it). So, I'm guessing it shouldn't be all that tough, but I'm not clear on what the steps would be to accomplish this.

和要清楚,我并不需要帮助的上面(我已经全部制定了),我想了解如何扩展视图的方式,它需要额外的功能所描述的手机的具体功能默认情况下,尽量不要有一遍遍地扰乱我的活动与同一code。

And to be clear, I don't need help with the Phone specific feature described above (I have that all worked out), I'm trying to understand how to extend View in a way that it takes on additional functionality by default, so as not to have to clutter my Activities with the same code over and over.

推荐答案

其实没有什么复杂有关。通常你会使用一个输入过滤到您的的EditText 在code和这将做的工作。但是,如果你看到一个模式,希望的EditText它总是表现这种方式,你可以创建一个自定义窗口小部件的方式:

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
    }
}

在XML布局你会简单地使用完整路径的自定义类,而不是EditText上:

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)" />

这篇关于什么是正确的方式来扩展的EditText给它附加的QUOT;默认&QUOT;功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆