android系统实现手机号添加分割符

原创
2016/08/12 15:54
阅读数 1.1K
通过调用系统的PhoneNumberFormattingTextWatcher类来实现
`
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.widget.TextView;

/**
 * 自动为手机号添加分割符
 * [@author](http://my.oschina.net/arthor) longpc
 *
 */
public final class PhoneNumberFormatter {
    private PhoneNumberFormatter() {}

    /**
     * Load {[@link](http://my.oschina.net/u/393) TextWatcherLoadAsyncTask} in a worker thread and set it to a {[@link](http://my.oschina.net/u/393) TextView}.
     */
    private static class TextWatcherLoadAsyncTask extends
            AsyncTask<Void, Void, PhoneNumberFormattingTextWatcher> {
        private final TextView mTextView;

        public TextWatcherLoadAsyncTask(TextView textView) {
            mTextView = textView;
        }

        @SuppressLint("NewApi")
		@Override
        protected PhoneNumberFormattingTextWatcher doInBackground(Void... params) {
            return new PhoneNumberFormattingTextWatcher();
        }

        @Override
        protected void onPostExecute(PhoneNumberFormattingTextWatcher watcher) {
            if (watcher == null || isCancelled()) {
                return; // May happen if we cancel the task.
            }
            // Setting a text changed listener is safe even after the view is detached.
            mTextView.addTextChangedListener(watcher);

            // Note changes the user made before onPostExecute() will not be formatted, but
            // once they type the next letter we format the entire text, so it's not a big deal.
            // (And loading PhoneNumberFormattingTextWatcher is usually fast enough.)
            // We could use watcher.afterTextChanged(mTextView.getEditableText()) to force format
            // the existing content here, but that could cause unwanted results.
            // (e.g. the contact editor thinks the user changed the content, and would save
            // when closed even when the user didn't make other changes.)
        }
    }

    /**
     * Delay-set {@link PhoneNumberFormattingTextWatcher} to a {@link TextView}.
     */
    public static final void setPhoneNumberFormattingTextWatcher(Context context,
            TextView textView) {
        new TextWatcherLoadAsyncTask(textView).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
    }
}
`

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部