android.widget.AutoCompleteTextView

Here are the examples of the java api android.widget.AutoCompleteTextView taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

211 Examples 7

19 Source : AutocompleteTextPreference.java
with GNU General Public License v3.0
from vbier

/**
 * EditTextPreference with auto completion.
 */
clreplaced AutocompleteTextPreference extends EditTextPreference {

    private final AutoCompleteTextView mTextView;

    public AutocompleteTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        mTextView = new AutoCompleteTextView(context, attrs);
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onBindDialogView(View view) {
        EditText editText = mTextView;
        editText.setText(getText());
        ViewParent oldParent = editText.getParent();
        if (oldParent != view) {
            if (oldParent != null) {
                ((ViewGroup) oldParent).removeView(editText);
            }
            onAddEditTextToDialogView(view, editText);
        }
    }

    /**
     * Returns the {@link AutoCompleteTextView} widget that will be shown in the dialog.
     *
     * @return The {@link AutoCompleteTextView} widget that will be shown in the dialog.
     */
    public AutoCompleteTextView getEditText() {
        return mTextView;
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);
        if (positiveResult) {
            String value = getEditText().getText().toString();
            if (callChangeListener(value)) {
                setText(value);
            }
        }
    }
}

19 Source : TransferFragment.java
with MIT License
from swapnibble

@Override
protected void setUpView(View view) {
    mRootView = view;
    // from, to, amount edit text
    AutoCompleteTextView etFrom = view.findViewById(R.id.et_from);
    AutoCompleteTextView etTo = view.findViewById(R.id.et_to);
    EditText etAmount = view.findViewById(R.id.et_amount);
    // click handler
    view.findViewById(R.id.btn_transfer).setOnClickListener(v -> onSend());
    etAmount.setOnEditorActionListener((textView, actionId, keyEvent) -> {
        if (EditorInfo.IME_ACTION_SEND == actionId) {
            onSend();
            return true;
        }
        return false;
    });
    // account history
    UiUtils.setupAccountHistory(etFrom, etTo);
}

19 Source : InputAccountDialog.java
with MIT License
from swapnibble

/**
 * Created by swapnibble on 2017-11-16.
 */
public clreplaced InputAccountDialog extends BaseDialog {

    private static final String TAG = InputAccountDialog.clreplaced.getSimpleName();

    private static final String ARG_INFO_TYPE = "type.for";

    private AccountInfoType mAccountInfoType = AccountInfoType.REGISTRATION;

    private Callback mCallback;

    private AutoCompleteTextView mEtAccount;

    public static InputAccountDialog newInstance(AccountInfoType infoType) {
        InputAccountDialog fragment = new InputAccountDialog();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_INFO_TYPE, infoType.name());
        fragment.setArguments(bundle);
        return fragment;
    }

    public InputAccountDialog setCallback(Callback callback) {
        mCallback = callback;
        return this;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle args = getArguments();
        mAccountInfoType = AccountInfoType.safeValueOf(args.getString(ARG_INFO_TYPE));
        View view = inflater.inflate(R.layout.dialog_input_account, container, false);
        ActivityComponent component = getActivityComponent();
        if (component != null) {
            component.inject(this);
        }
        return view;
    }

    @Override
    protected void setUpView(View view) {
        if (AccountInfoType.ACTIONS.equals(mAccountInfoType)) {
            ((AutoCompleteTextView) view.findViewById(R.id.et_pos)).setText("-1");
            ((AutoCompleteTextView) view.findViewById(R.id.et_offset)).setText("-20");
        } else {
            view.findViewById(R.id.et_pos).setVisibility(View.GONE);
            view.findViewById(R.id.et_offset).setVisibility(View.GONE);
        }
        // replacedle
        ((TextView) view.findViewById(R.id.tv_replacedle)).setText(mAccountInfoType.getreplacedleId());
        // edit view
        mEtAccount = view.findViewById(R.id.et_account);
        UiUtils.setupAccountHistory(mEtAccount);
        // ok
        view.findViewById(R.id.btn_ok).setOnClickListener(v -> {
            if (null != mCallback) {
                if (AccountInfoType.ACTIONS.equals(mAccountInfoType)) {
                    mCallback.onAccountEntered(mEtAccount.getText().toString(), Utils.parseIntSafely(((AutoCompleteTextView) view.findViewById(R.id.et_pos)).getText().toString(), -1), Utils.parseIntSafely(((AutoCompleteTextView) view.findViewById(R.id.et_offset)).getText().toString(), -20), mAccountInfoType);
                } else {
                    mCallback.onAccountEntered(mEtAccount.getText().toString(), -1, -1, mAccountInfoType);
                }
            }
            dismiss();
        });
        // cancel
        view.findViewById(R.id.btn_cancel).setOnClickListener(v -> dismiss());
    }

    public void show(FragmentManager fragmentManager) {
        super.show(fragmentManager, TAG);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    public interface Callback {

        void onAccountEntered(String account, int position, int offset, AccountInfoType infoType);
    }
}

19 Source : LoginActivity.java
with Apache License 2.0
from stytooldex

// import android.support.v7.app.AppCompatActivity;
/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced LoginActivity extends Fragment {

    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    // private View mLoginFormView;
    // private MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
    /**
     * 将用户与设备绑定起来
     *
     * @param user
     */
    private void bindUserIdAndDriverice(final MyUser user) {
        ;
        BmobQuery<MyUserInstallation> query = new BmobQuery<MyUserInstallation>();
        query.addWhereEqualTo("installationId", BmobInstallationManager.getInstallationId());
        query.findObjectsObservable(MyUserInstallation.clreplaced).subscribe(new Action1<List<MyUserInstallation>>() {

            @Override
            public void call(List<MyUserInstallation> installations) {
                if (installations.size() > 0) {
                    if (installations.size() > 0) {
                        MyUserInstallation myUserInstallation = installations.get(0);
                        myUserInstallation.setUid(user.getObjectId());
                        myUserInstallation.update(new UpdateListener() {

                            @Override
                            public void done(BmobException e) {
                                if (e == null) {
                                } else {
                                }
                            }
                        });
                    }
                } else {
                // toastE("后台不存在此设备Id的数据,请确认此设备Id是否正确!\n" + id);
                }
            }
        }, new Action1<Throwable>() {

            @Override
            public void call(Throwable throwable) {
            // toastE("查询设备数据失败:" + throwable.getMessage());
            }
        });
    }

    private void attemptLogin() {
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            focusView.requestFocus();
        } else {
            lxwLogin(email, preplacedword);
        // showProgress(true,email,preplacedword);
        }
    }

    private boolean isEmailValid(String email) {
        // TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }

    private void lxwLogin(String email, String preplacedword) {
        MyUser user = new MyUser();
        user.setEmail(email);
        user.setPreplacedword(preplacedword);
        BmobUser.loginByAccount(email, preplacedword, new LogInListener<MyUser>() {

            @Override
            public void done(MyUser user, BmobException e) {
                if (user != null) {
                    bindUserIdAndDriverice(user);
                    getActivity().finish();
                } else {
                    Toast.makeText(getActivity(), "登录失败!错误信息:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: Implement this method
        View view = inflater.inflate(R.layout.activity_login, null);
        mEmailView = (AutoCompleteTextView) view.findViewById(R.id.email);
        // populateAutoComplete();
        mPreplacedwordView = (EditText) view.findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = view.findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        Button mEmailSignInButton0 = view.findViewById(R.id.email_sign_in_button0);
        mEmailSignInButton0.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                LayoutInflater inflater = LayoutInflater.from(getActivity());
                View view2 = inflater.inflate(R.layout.getda, null);
                final Button fab_2 = view2.findViewById(R.id.ahnButton1);
                final Button fab_3 = view2.findViewById(R.id.ahnButton12);
                EditText ediusername = view2.findViewById(R.id.ahnEditText1);
                EditText ediemail = view2.findViewById(R.id.ahnEditText12);
                final String username = ediusername.getText().toString().trim();
                final String email = ediemail.getText().toString().trim();
                fab_2.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        BmobUser.loginByAccount(username, email, new LogInListener<MyUser>() {

                            @Override
                            public void done(MyUser user, BmobException e) {
                                if (user != null) {
                                    bindUserIdAndDriverice(user);
                                    getActivity().finish();
                                // Log.i("smile","用户登陆成功");
                                }
                            }
                        });
                        fab_3.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View view) {
                                LayoutInflater inflater = LayoutInflater.from(getActivity());
                                View view2 = inflater.inflate(R.layout.getde0, null);
                                EditText ediusername = view2.findViewById(R.id.ahnEditText1);
                                EditText ediemail = view2.findViewById(R.id.ahnEditText12);
                                final String username = ediusername.getText().toString().trim();
                                final String email = ediemail.getText().toString().trim();
                                Button fab_2 = (Button) view2.findViewById(R.id.ahnButton1);
                                fab_2.setOnClickListener(new View.OnClickListener() {

                                    @Override
                                    public void onClick(View view) {
                                        TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(android.support.v4.app.FragmentActivity.TELEPHONY_SERVICE);
                                        MyUser user = new MyUser();
                                        // 设置手机号码(必填)
                                        user.setMobilePhoneNumber(username);
                                        // user.setUsername(xxx);                  //设置用户名,如果没有传用户名,则默认为手机号码
                                        // 设置用户密码
                                        user.setPreplacedword(email);
                                        user.setScore(10);
                                        user.setSex(1);
                                        user.setNum("vs");
                                        user.setAge(1);
                                        user.setAddress("不激活");
                                        user.setHol(tm.getDeviceId());
                                        user.setid("520");
                                        user.setGender(false);
                                        user.setGen_(false);
                                        user.setGen_v(false);
                                        user.setPlayScore(1);
                                        user.setSignScore(1);
                                        user.setPlayScore_(1);
                                        user.setPlayScore_s(1);
                                        user.setGame("v");
                                        user.setCardNumber("v");
                                        user.setBankName("v");
                                        user.signOrLogin("验证码", new SaveListener<MyUser>() {

                                            @Override
                                            public void done(MyUser user, BmobException e) {
                                                if (e == null) {
                                                // toast("注册或登录成功");
                                                // Log.i("smile", ""+user.getUsername()+"-"+user.getAge()+"-"+user.getObjectId());
                                                } else {
                                                // toast("失败:" + e.getMessage());
                                                }
                                            }
                                        });
                                    }
                                });
                                AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity());
                                builder1.setView(view2).setreplacedle("AdapterView").setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).setPositiveButton("不再弹出", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                    // Toast.makeText(ws_Main3Activity.this, "下载安装后就不再弹出了", Toast.LENGTH_SHORT).show();
                                    }
                                }).setCancelable(false).create().show();
                            }
                        });
                    }
                });
                AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity());
                builder1.setView(view2).setreplacedle("AdapterView").setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).setPositiveButton("不再弹出", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    // Toast.makeText(ws_Main3Activity.this, "下载安装后就不再弹出了", Toast.LENGTH_SHORT).show();
                    }
                }).setCancelable(false).create().show();
            }
        });
        // mLoginFormView = view.findViewById(R.id.login_form);
        // mProgressView = view.findViewById(R.id.login_progress);
        // 注册退出广播
        // IntentFilter filter = new IntentFilter();
        // filter.addAction(Constant.ACTION_REGISTER_SUCCESS_FINISH);
        // getActivity().registerReceiver(myBroadcastReceiver, filter);
        return view;
    }
}

19 Source : DropdownMenuEndIconDelegate.java
with Apache License 2.0
from material-components

/* Add ripple effect to non editable layouts. */
private void addRippleEffect(@NonNull AutoCompleteTextView editText) {
    if (isEditable(editText)) {
        return;
    }
    int boxBackgroundMode = textInputLayout.getBoxBackgroundMode();
    MaterialShapeDrawable boxBackground = textInputLayout.getBoxBackground();
    int rippleColor = MaterialColors.getColor(editText, R.attr.colorControlHighlight);
    int[][] states = new int[][] { new int[] { android.R.attr.state_pressed }, new int[] {} };
    if (boxBackgroundMode == TextInputLayout.BOX_BACKGROUND_OUTLINE) {
        addRippleEffectOnOutlinedLayout(editText, rippleColor, states, boxBackground);
    } else if (boxBackgroundMode == TextInputLayout.BOX_BACKGROUND_FILLED) {
        addRippleEffectOnFilledLayout(editText, rippleColor, states, boxBackground);
    }
}

19 Source : SearchDialog.java
with Apache License 2.0
from lulululbj

private boolean isEmpty(AutoCompleteTextView actv) {
    return TextUtils.getTrimmedLength(actv.getText()) == 0;
}

19 Source : DropdownMenuEndIconDelegate.java
with Apache License 2.0
from covidsafewatch

/* access modifiers changed from: private */
public void addRippleEffect(AutoCompleteTextView autoCompleteTextView) {
    if (autoCompleteTextView.getKeyListener() == null) {
        int boxBackgroundMode = this.textInputLayout.getBoxBackgroundMode();
        MaterialShapeDrawable boxBackground = this.textInputLayout.getBoxBackground();
        int color = MaterialColors.getColor(autoCompleteTextView, R.attr.colorControlHighlight);
        int[][] iArr = { new int[] { 16842919 }, new int[0] };
        if (boxBackgroundMode == 2) {
            addRippleEffectOnOutlinedLayout(autoCompleteTextView, color, iArr, boxBackground);
        } else if (boxBackgroundMode == 1) {
            addRippleEffectOnFilledLayout(autoCompleteTextView, color, iArr, boxBackground);
        }
    }
}

19 Source : AutoCompleteEditTextWrapper.java
with Apache License 2.0
from AnywhereSoftware

/**
 * Forces the drop down list to appear.
 */
public void ShowDropDown() {
    AutoCompleteTextView a = (AutoCompleteTextView) getObject();
    a.showDropDown();
}

18 Source : MainActivity.java
with Apache License 2.0
from youlookwhat

/**
 * Link to: https://github.com/youlookwhat/WebViewStudy
 * contact me: https://www.jianshu.com/u/e43c6e979831
 */
public clreplaced MainActivity extends AppCompatActivity implements View.OnClickListener {

    // 是否开启了主页,没有开启则会返回主页
    public static boolean isLaunch = false;

    private AutoCompleteTextView etSearch;

    private RadioButton rbSystem;

    private int state = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.colorPrimary), 0);
        initView();
        isLaunch = true;
    }

    private void initView() {
        findViewById(R.id.bt_deeplink).setOnClickListener(this);
        findViewById(R.id.bt_openUrl).setOnClickListener(this);
        findViewById(R.id.bt_baidu).setOnClickListener(this);
        findViewById(R.id.bt_movie).setOnClickListener(this);
        findViewById(R.id.bt_upload_photo).setOnClickListener(this);
        findViewById(R.id.bt_call).setOnClickListener(this);
        findViewById(R.id.bt_java_js).setOnClickListener(this);
        findViewById(R.id.bt_toolbar).setOnClickListener(this);
        rbSystem = findViewById(R.id.rb_system);
        etSearch = findViewById(R.id.et_search);
        rbSystem.setChecked(true);
        TextView tvVersion = findViewById(R.id.tv_version);
        tvVersion.setText(String.format("❤版本:v%s", BuildConfig.VERSION_NAME));
        tvVersion.setOnClickListener(this);
        /**
         * 处理键盘搜索键
         */
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    openUrl();
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.bt_openUrl:
                openUrl();
                break;
            case // 百度一下
            R.id.bt_baidu:
                state = 0;
                String baiDuUrl = "http://www.baidu.com";
                loadUrl(baiDuUrl, getString(R.string.text_baidu));
                break;
            case // 网络视频
            R.id.bt_movie:
                state = 0;
                String movieUrl = "https://sv.baidu.com/videoui/page/videoland?context=%7B%22nid%22%3A%22sv_5861863042579737844%22%7D&pd=feedtab_h5";
                loadUrl(movieUrl, getString(R.string.text_movie));
                break;
            case // 上传图片
            R.id.bt_upload_photo:
                state = 0;
                String uploadUrl = "file:///android_replacedet/upload_photo.html";
                loadUrl(uploadUrl, getString(R.string.text_upload_photo));
                break;
            case // 打电话、发短信、发邮件、JS
            R.id.bt_call:
                state = 1;
                String callUrl = "file:///android_replacedet/callsms.html";
                loadUrl(callUrl, getString(R.string.text_js));
                break;
            case // js与android原生代码互调
            R.id.bt_java_js:
                state = 2;
                String javaJs = "file:///android_replacedet/java_js.html";
                loadUrl(javaJs, getString(R.string.js_android));
                break;
            case // DeepLink通过网页跳入App
            R.id.bt_deeplink:
                state = 0;
                String deepLinkUrl = "file:///android_replacedet/deeplink.html";
                loadUrl(deepLinkUrl, getString(R.string.deeplink));
                break;
            case // 与ToolBar联动,自定义WebView
            R.id.bt_toolbar:
                CoordinatorWebActivity.loadUrl(this, "http://www.baidu.com", "百度一下", 0);
                break;
            case R.id.tv_version:
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                builder.setreplacedle("感谢");
                builder.setMessage("开源不易,给作者一个star好吗?😊");
                builder.setNegativeButton("已给", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "感谢老铁~", Toast.LENGTH_LONG).show();
                    }
                });
                builder.setPositiveButton("去star", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        state = 0;
                        loadUrl("https://github.com/youlookwhat/WebViewStudy", "WebViewStudy");
                    }
                });
                builder.show();
                break;
            default:
                break;
        }
    }

    /**
     * 打开网页
     */
    private void openUrl() {
        state = 0;
        String url = ByWebTools.getUrl(etSearch.getText().toString().trim());
        loadUrl(!TextUtils.isEmpty(url) ? url : "https://github.com/youlookwhat/WebViewStudy", "详情");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.gereplacedemId()) {
            case R.id.actionbar_update:
                state = 0;
                loadUrl("http://d.6short.com/webviewstudy", "网页浏览器 - fir.im");
                break;
            case R.id.actionbar_about:
                state = 0;
                loadUrl("https://github.com/youlookwhat/WebViewStudy", "WebViewStudy");
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void loadUrl(String mUrl, String mreplacedle) {
        if (rbSystem.isChecked()) {
            // WebViewActivity.loadUrl(this, mUrl, mreplacedle);
            ByWebViewActivity.loadUrl(this, mUrl, mreplacedle, state);
        } else {
            X5WebViewActivity.loadUrl(this, mUrl, mreplacedle);
        }
    }

    public static void start(Context context) {
        context.startActivity(new Intent(context, MainActivity.clreplaced));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isLaunch = false;
    }
}

18 Source : LoginActivity.java
with Apache License 2.0
from xzwc

/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced LoginActivity extends BaseActivity implements LoaderCallbacks<Cursor>, LoginView {

    /**
     * Id to idenreplacedy READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "[email protected]:hello", "[email protected]:world" };

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();
        mPreplacedwordView = (EditText) findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    @Override
    public void setupActivityComponent() {
        AuthApplication.get(this).getAppComponent().plus(new LoginModule(this)).inject(this);
    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }
        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE).setAction(android.R.string.ok, new View.OnClickListener() {

                @Override
                @TargetApi(Build.VERSION_CODES.M)
                public void onClick(View v) {
                    requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
                }
            });
        } else {
            requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid preplacedword, if the user entered one.
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, preplacedword);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isEmailValid(String email) {
        // TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact.
        Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses.
        ContactsContract.Contacts.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }, // Show primary email addresses first. Note that there won't be
        // a primary email address if the user hasn't specified one.
        ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }
        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        // Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter = new ArrayAdapter<>(LoginActivity.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
        mEmailView.setAdapter(adapter);
    }

    @Override
    public void loginSuccess() {
    }

    @Override
    public void loginFailure() {
    }

    private interface ProfileQuery {

        String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY };

        int ADDRESS = 0;

        int IS_PRIMARY = 1;
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public clreplaced UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;

        private final String mPreplacedword;

        UserLoginTask(String email, String preplacedword) {
            mEmail = email;
            mPreplacedword = preplacedword;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the preplacedword matches.
                    return pieces[1].equals(mPreplacedword);
                }
            }
            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if (success) {
                finish();
            } else {
                mPreplacedwordView.setError(getString(R.string.error_incorrect_preplacedword));
                mPreplacedwordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

18 Source : LoginActivity.java
with MIT License
from why168

/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {

    /**
     * Id to idenreplacedy READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "[email protected]:hello", "[email protected]:world" };

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();
        mPreplacedwordView = (EditText) findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.email_login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }
        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE).setAction(android.R.string.ok, new View.OnClickListener() {

                @Override
                @TargetApi(Build.VERSION_CODES.M)
                public void onClick(View v) {
                    requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
                }
            });
        } else {
            requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid preplacedword, if the user entered one.
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, preplacedword);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isEmailValid(String email) {
        // TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact.
        Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses.
        ContactsContract.Contacts.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }, // Show primary email addresses first. Note that there won't be
        // a primary email address if the user hasn't specified one.
        ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }
        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        // Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter = new ArrayAdapter<>(LoginActivity.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
        mEmailView.setAdapter(adapter);
    }

    private interface ProfileQuery {

        String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY };

        int ADDRESS = 0;

        int IS_PRIMARY = 1;
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public clreplaced UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;

        private final String mPreplacedword;

        UserLoginTask(String email, String preplacedword) {
            mEmail = email;
            mPreplacedword = preplacedword;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the preplacedword matches.
                    return pieces[1].equals(mPreplacedword);
                }
            }
            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if (success) {
                finish();
            } else {
                mPreplacedwordView.setError(getString(R.string.error_incorrect_preplacedword));
                mPreplacedwordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

18 Source : LoginActivity.java
with Apache License 2.0
from tinyvampirepudge

/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced LoginActivity extends BaseActivity implements LoaderCallbacks<Cursor> {

    /**
     * Id to idenreplacedy READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "[email protected]:hello", "[email protected]:world" };

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @Override
    protected int setContentLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void buildContentView() {
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();
        mPreplacedwordView = (EditText) findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    @Override
    protected void initViewData() {
    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }
        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE).setAction(android.R.string.ok, new View.OnClickListener() {

                @Override
                @TargetApi(Build.VERSION_CODES.M)
                public void onClick(View v) {
                    requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
                }
            });
        } else {
            requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid preplacedword, if the user entered one.
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, preplacedword);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isEmailValid(String email) {
        return email.contains("@");
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        return preplacedword.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact.
        Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses.
        ContactsContract.Contacts.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }, // Show primary email addresses first. Note that there won't be
        // a primary email address if the user hasn't specified one.
        ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }
        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        // Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter = new ArrayAdapter<>(LoginActivity.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
        mEmailView.setAdapter(adapter);
    }

    private interface ProfileQuery {

        String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY };

        int ADDRESS = 0;

        int IS_PRIMARY = 1;
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public clreplaced UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;

        private final String mPreplacedword;

        UserLoginTask(String email, String preplacedword) {
            mEmail = email;
            mPreplacedword = preplacedword;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the preplacedword matches.
                    return pieces[1].equals(mPreplacedword);
                }
            }
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if (success) {
                finish();
            } else {
                mPreplacedwordView.setError(getString(R.string.error_incorrect_preplacedword));
                mPreplacedwordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

18 Source : EditTagsDialog.java
with GNU General Public License v3.0
from TBog

public clreplaced EditTagsDialog extends DialogFragment<Set<String>> {

    private final ArraySet<String> mTagList = new ArraySet<>();

    private TagsAdapter mAdapter;

    private AutoCompleteTextView mNewTag;

    @Override
    protected int layoutRes() {
        return R.layout.dialog_edit_tags;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup root = (ViewGroup) super.onCreateView(inflater, container, savedInstanceState);
        replacedert root != null;
        Context context = inflater.getContext();
        // make a layout for the entry we are changing
        Bundle args = getArguments() != null ? getArguments() : new Bundle();
        String entryId = args.getString("entryId", "");
        TBApplication app = TBApplication.getApplication(context);
        EntryItem entry = app.getDataHandler().getPojo(entryId);
        if (entry != null) {
            int drawFlags = EntryItem.FLAG_DRAW_LIST | EntryItem.FLAG_DRAW_NAME | EntryItem.FLAG_DRAW_ICON;
            View entryView = inflater.inflate(entry.getResultLayout(drawFlags), root, false);
            entryView.setId(R.id.preview);
            root.addView(entryView, 0);
            app.ui().setResultListPref(entryView);
        }
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Context context = view.getContext();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            view.setClipToOutline(true);
        }
        Bundle args = getArguments() != null ? getArguments() : new Bundle();
        String entryId = args.getString("entryId", "");
        String entryName = args.getString("entryName", "");
        // show the app we are changing
        EntryItem entry = TBApplication.getApplication(context).getDataHandler().getPojo(entryId);
        if (entry == null) {
            dismiss();
            return;
        }
        int drawFlags = EntryItem.FLAG_DRAW_LIST | EntryItem.FLAG_DRAW_NAME | EntryItem.FLAG_DRAW_ICON;
        entry.displayResult(view.findViewById(R.id.preview), drawFlags);
        // prepare the grid with all the tags
        mAdapter = new TagsAdapter(mTagList);
        GridView gridView = view.findViewById(R.id.grid);
        gridView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener((adapter, v, position) -> removeTag(adapter.gereplacedem(position)));
        // initialize new tag EditView
        mNewTag = view.findViewById(R.id.newTag);
        mNewTag.addTextChangedListener(new Texreplacedcher() {

            public void afterTextChanged(Editable s) {
                // Auto left-trim text.
                if (s.length() > 0 && s.charAt(0) == ' ')
                    s.delete(0, 1);
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
        });
        mNewTag.setOnEditorActionListener((v, actionId, event) -> {
            if (event == null) {
                if (actionId != EditorInfo.IME_ACTION_NONE) {
                    String tag = mNewTag.getText().toString();
                    if (tag.isEmpty()) {
                        onConfirm(mTagList);
                        dismiss();
                        return true;
                    }
                    addTag(tag);
                    return true;
                }
            } else if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                if (event.getAction() == KeyEvent.ACTION_UP) {
                    String tag = mNewTag.getText().toString();
                    addTag(tag);
                }
                return true;
            }
            return false;
        });
        // set the auto complete list
        {
            List<String> allTags = new ArrayList<>(TBApplication.tagsHandler(context).getValidTags());
            Collections.sort(allTags);
            mNewTag.setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, allTags));
        }
        // initialize add tag button
        ImageView addTag = view.findViewById(R.id.addTag);
        addTag.setOnClickListener(v -> {
            String tag = mNewTag.getText().toString();
            addTag(tag);
        });
        // OK button
        {
            View button = view.findViewById(android.R.id.button1);
            button.setOnClickListener(v -> {
                String tag = mNewTag.getText().toString();
                addTag(tag);
                onConfirm(mTagList);
                dismiss();
            });
        }
        // CANCEL button
        {
            View button = view.findViewById(android.R.id.button2);
            button.setOnClickListener(v -> dismiss());
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        mNewTag.post(() -> {
            mNewTag.requestFocus();
            InputMethodManager mgr = (InputMethodManager) requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            replacedert mgr != null;
            mgr.showSoftInput(mNewTag, InputMethodManager.SHOW_IMPLICIT);
        });
    }

    private void addTag(String tag) {
        tag = tag.trim();
        if (tag.length() == 0)
            return;
        mTagList.add(tag);
        mAdapter.notifyDataSetChanged();
        mNewTag.setText("");
    }

    private void removeTag(String tag) {
        mTagList.remove(tag);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Context context = getActivity();
        replacedert context != null;
        Bundle args = getArguments() != null ? getArguments() : new Bundle();
        String entryId = args.getString("entryId", "");
        TagsHandler tagsHandler = TBApplication.tagsHandler(context);
        mTagList.clear();
        mTagList.addAll(tagsHandler.getTags(entryId));
        mAdapter.notifyDataSetChanged();
    }

    static clreplaced TagsAdapter extends BaseAdapter {

        private final ArraySet<String> mTags;

        private OnItemClickListener mOnItemClickListener = null;

        public interface OnItemClickListener {

            void onItemClick(TagsAdapter adapter, View view, int position);
        }

        TagsAdapter(@NonNull ArraySet<String> tags) {
            mTags = tags;
        }

        void setOnItemClickListener(OnItemClickListener listener) {
            mOnItemClickListener = listener;
        }

        @Override
        public int getCount() {
            return mTags.size();
        }

        @Override
        public String gereplacedem(int position) {
            return mTags.valueAt(position);
        }

        @Override
        public long gereplacedemId(int position) {
            return gereplacedem(position).hashCode();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final View view;
            if (convertView == null) {
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.edit_tag_item, parent, false);
            } else {
                view = convertView;
            }
            ViewHolder holder = view.getTag() instanceof ViewHolder ? (ViewHolder) view.getTag() : new ViewHolder(view);
            String content = gereplacedem(position);
            holder.setContent(content);
            holder.buttonView.setOnClickListener(v -> {
                if (mOnItemClickListener != null)
                    mOnItemClickListener.onItemClick(TagsAdapter.this, v, position);
            });
            return view;
        }

        static clreplaced ViewHolder {

            TextView textView;

            View buttonView;

            ViewHolder(View itemView) {
                itemView.setTag(this);
                textView = itemView.findViewById(android.R.id.text1);
                buttonView = itemView.findViewById(android.R.id.button1);
            }

            public void setContent(CharSequence content) {
                textView.setText(content);
            }
        }
    }
}

18 Source : DownLoadAddActivity.java
with Apache License 2.0
from Tamicer

/**
 * DownLoadAddActivity
 */
public clreplaced DownLoadAddActivity extends AppCompatActivity {

    // UI references.
    private AutoCompleteTextView mUrlView;

    Button mGoDownButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_down_load_add);
        ButterKnife.bind(this, this);
        // Set up the url form.
        mUrlView = (AutoCompleteTextView) findViewById(R.id.down_Loadurl);
        mGoDownButton = (Button) findViewById(R.id.down_in_button);
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid url, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    @OnClick(R.id.down_in_button)
    void attemptDown() {
        // Reset errors.
        mUrlView.setError(null);
        // Store values at the time of the login attempt.
        String url = mUrlView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid url address.
        if (TextUtils.isEmpty(url)) {
            mUrlView.setError(getString(R.string.error_field_required));
            Toast.makeText(this, R.string.error_field_required, Toast.LENGTH_SHORT).show();
            focusView = mUrlView;
            cancel = true;
            focusView.requestFocus();
            return;
        }
        // Check for a valid url address.
        if (HttpUrl.parse(url) == null || TextUtils.isEmpty(HttpUrl.parse(url).url().toString())) {
            mUrlView.setError(getString(R.string.error_field_required));
            Toast.makeText(this, R.string.error_invalid_url, Toast.LENGTH_SHORT).show();
            focusView = mUrlView;
            cancel = true;
            focusView.requestFocus();
            return;
        }
        // perform the down attempt.
        new Download.Builder().url(url).priority(Priority.LOW).type(Type.NORMAL).build(this).start();
    }
}

18 Source : UiUtils.java
with MIT License
from swapnibble

public static void setupAccountHistory(AutoCompleteTextView... autoTextViewArray) {
    for (AutoCompleteTextView actv : autoTextViewArray) {
        AccountAdapter adapter = new AccountAdapter(actv.getContext(), R.layout.account_suggestion, R.id.eos_account);
        if (actv instanceof MultiAutoCompleteTextView) {
            ((MultiAutoCompleteTextView) actv).setTokenizer(new WhitSpaceTokenizer());
        }
        actv.setThreshold(1);
        actv.setAdapter(adapter);
    }
}

18 Source : LoginActivity.java
with MIT License
from stytooldex

// import android.support.v7.app.AppCompatActivity;
/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced LoginActivity extends Fragment {

    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    // private View mLoginFormView;
    private MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();

    private void attemptLogin() {
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            focusView.requestFocus();
        } else {
            lxwLogin(email, preplacedword);
        // showProgress(true,email,preplacedword);
        }
    }

    private boolean isEmailValid(String email) {
        // TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }

    private void lxwLogin(String email, String preplacedword) {
        MyUser user = new MyUser();
        user.setEmail(email);
        user.setPreplacedword(preplacedword);
        BmobUser.loginByAccount(getActivity(), email, preplacedword, new LogInListener<MyUser>() {

            @Override
            public void done(MyUser myUser, BmobException e) {
                if (myUser != null) {
                    // Toast.makeText(getActivity(), "用户登录成功", Toast.LENGTH_SHORT).show();
                    bindUserIdAndDriverice(myUser);
                } else {
                    mProgressView.setVisibility(View.GONE);
                    // mLoginFormView.setVisibility(View.VISIBLE);
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setMessage("登录失败,可能是邮箱或者密码错误!").create().show();
                // Log.e(TAG, "---login_error----" + e);
                }
            }
        });
    }

    /**
     * 将用户与设备绑定起来
     *
     * @param user
     */
    private void bindUserIdAndDriverice(final MyUser user) {
        // Log.e(TAG, "===bindUserIdAndDriverce==");
        BmobQuery<MyUserInstallation> query = new BmobQuery<MyUserInstallation>();
        query.addWhereEqualTo("installationId", BmobInstallation.getInstallationId(getActivity()));
        query.findObjects(getActivity(), new FindListener<MyUserInstallation>() {

            @Override
            public void onSuccess(List<MyUserInstallation> list) {
                // */ Log.e(TAG,"==list=size==="+list.size());
                if (list.size() > 0) {
                    // Log.e(TAG, "===list===: " + list.get(0).toString());
                    MyUserInstallation myUserInstallation = list.get(0);
                    myUserInstallation.setUid(user.getObjectId());
                    myUserInstallation.update(getActivity(), new UpdateListener() {

                        @Override
                        public void onSuccess() {
                            // Log.e(TAG, "===设备信息更新成功===");
                            getActivity().finish();
                        }

                        @Override
                        public void onFailure(int i, String s) {
                        // Log.e(TAG, "===设备信息更新失败:" + s);
                        }
                    });
                }
            }

            @Override
            public void onError(int i, String s) {
            // Log.e(TAG, "===find erro==" + s);
            }
        });
    }

    private interface ProfileQuery {

        String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY };

        int ADDRESS = 0;

        int IS_PRIMARY = 1;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: Implement this method
        View view = inflater.inflate(R.layout.activity_login, null);
        mEmailView = (AutoCompleteTextView) view.findViewById(R.id.email);
        // populateAutoComplete();
        mPreplacedwordView = (EditText) view.findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) view.findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        // mLoginFormView = view.findViewById(R.id.login_form);
        mProgressView = view.findViewById(R.id.login_progress);
        // 注册退出广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_REGISTER_SUCCESS_FINISH);
        getActivity().registerReceiver(myBroadcastReceiver, filter);
        return view;
    }

    private clreplaced MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && intent.getAction().equals(Constant.ACTION_REGISTER_SUCCESS_FINISH)) {
                getActivity().finish();
            }
        }
    }
}

18 Source : InputtipsActivity.java
with MIT License
from ShihooWang

/**
 * 输入提示功能实现
 */
public clreplaced InputtipsActivity extends Activity implements Texreplacedcher, InputtipsListener {

    private String city = "北京";

    private AutoCompleteTextView mKeywordText;

    private ListView minputlist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inputtip);
        minputlist = (ListView) findViewById(R.id.inputlist);
        mKeywordText = (AutoCompleteTextView) findViewById(R.id.input_edittext);
        mKeywordText.addTextChangedListener(this);
    }

    @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) {
        String newText = s.toString().trim();
        InputtipsQuery inputquery = new InputtipsQuery(newText, city);
        inputquery.setCityLimit(true);
        Inputtips inputTips = new Inputtips(InputtipsActivity.this, inputquery);
        inputTips.setInputtipsListener(this);
        inputTips.requestInputtipsAsyn();
    }

    @Override
    public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
    }

    /**
     * 输入提示结果的回调
     * @param tipList
     * @param rCode
     */
    @Override
    public void onGetInputtips(final List<Tip> tipList, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            List<HashMap<String, String>> listString = new ArrayList<HashMap<String, String>>();
            if (tipList != null) {
                int size = tipList.size();
                for (int i = 0; i < size; i++) {
                    Tip tip = tipList.get(i);
                    if (tip != null) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put("name", tipList.get(i).getName());
                        map.put("address", tipList.get(i).getDistrict());
                        listString.add(map);
                    }
                }
                SimpleAdapter aAdapter = new SimpleAdapter(getApplicationContext(), listString, R.layout.item_layout, new String[] { "name", "address" }, new int[] { R.id.poi_field_id, R.id.poi_value_id });
                minputlist.setAdapter(aAdapter);
                aAdapter.notifyDataSetChanged();
            }
        } else {
            ToastUtil.showerror(this.getApplicationContext(), rCode);
        }
    }
}

18 Source : LoginActivity.java
with Apache License 2.0
from RealMoMo

/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {

    /**
     * Id to idenreplacedy READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "[email protected]:hello", "[email protected]:world" };

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();
        mPreplacedwordView = (EditText) findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }
        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE).setAction(android.R.string.ok, new View.OnClickListener() {

                @Override
                @TargetApi(Build.VERSION_CODES.M)
                public void onClick(View v) {
                    requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
                }
            });
        } else {
            requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid preplacedword, if the user entered one.
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, preplacedword);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isEmailValid(String email) {
        // TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact.
        Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses.
        ContactsContract.Contacts.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }, // Show primary email addresses first. Note that there won't be
        // a primary email address if the user hasn't specified one.
        ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }
        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        // Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter = new ArrayAdapter<>(LoginActivity.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
        mEmailView.setAdapter(adapter);
    }

    private interface ProfileQuery {

        String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY };

        int ADDRESS = 0;

        int IS_PRIMARY = 1;
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public clreplaced UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;

        private final String mPreplacedword;

        UserLoginTask(String email, String preplacedword) {
            mEmail = email;
            mPreplacedword = preplacedword;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the preplacedword matches.
                    return pieces[1].equals(mPreplacedword);
                }
            }
            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if (success) {
                finish();
            } else {
                mPreplacedwordView.setError(getString(R.string.error_incorrect_preplacedword));
                mPreplacedwordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

18 Source : AutoCompleteTextViewSubject.java
with Apache License 2.0
from pkware

/**
 * Propositions for {@link AutoCompleteTextView} subjects.
 */
public clreplaced AutoCompleteTextViewSubject extends AbstractTextViewSubject<AutoCompleteTextView> {

    @Nullable
    private final AutoCompleteTextView actual;

    public AutoCompleteTextViewSubject(@Nonnull FailureMetadata failureMetadata, @Nullable AutoCompleteTextView actual) {
        super(failureMetadata, actual);
        this.actual = actual;
    }

    public void hasEnoughToFilter() {
        check("enoughToFilter()").that(actual.enoughToFilter()).isTrue();
    }

    public void hasAdapter(@Nullable ListAdapter adapter) {
        check("getAdapter()").that(actual.getAdapter()).isSameInstanceAs(adapter);
    }

    @TargetApi(JELLY_BEAN)
    public void hasCompletionHint(@Nullable String hint) {
        check("getCompletionHint()").that(actual.getCompletionHint().toString()).isEqualTo(hint);
    }

    public void hasCompletionHint(@StringRes int resId) {
        hasCompletionHint(actual.getContext().getString(resId));
    }

    public void hasDropDownAnchor(int id) {
        check("getDropDownAnchor()").that(actual.getDropDownAnchor()).isEqualTo(id);
    }

    public void hasDropDownBackground(@Nullable Drawable background) {
        check("getDropDownBackground()").that(actual.getDropDownBackground()).isSameInstanceAs(background);
    }

    public void hasDropDownHeight(int height) {
        check("getDropDownHeight()").that(actual.getDropDownHeight()).isEqualTo(height);
    }

    public void hasDropDownHorizontalOffset(int offset) {
        check("getDropDownHorizontalOffset()").that(actual.getDropDownHorizontalOffset()).isEqualTo(offset);
    }

    public void hasDropDownVerticalOffset(int offset) {
        check("getDropDownVerticalOffset()").that(actual.getDropDownVerticalOffset()).isEqualTo(offset);
    }

    public void hasDropDownWidth(int width) {
        check("getDropDownWidth()").that(actual.getDropDownWidth()).isEqualTo(width);
    }

    public void hasListSelection(int position) {
        check("getListSelection()").that(actual.getListSelection()).isEqualTo(position);
    }

    public void hasThreshold(int threshold) {
        check("getThreshold()").that(actual.getThreshold()).isEqualTo(threshold);
    }

    public void isPerformingCompletion() {
        check("isPerformingCompletion()").that(actual.isPerformingCompletion()).isTrue();
    }

    public void isNotPerformingCompletion() {
        check("isPerformingCompletion()").that(actual.isPerformingCompletion()).isFalse();
    }

    public void isShowingPopup() {
        check("isPopupShowing()").that(actual.isPopupShowing()).isTrue();
    }

    public void isNotShowingPopup() {
        check("isPopupShowing()").that(actual.isPopupShowing()).isFalse();
    }
}

18 Source : LoginActivity.java
with Apache License 2.0
from mxxlei

/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced LoginActivity extends BaseActivity implements OnClickListener, AppPrepare.AppPrepareCallback {

    /**
     * Id to idenreplacedy READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "[email protected]:hello", "[email protected]:world" };

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        mPreplacedwordView = (EditText) findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
        findViewById(R.id.registe).setOnClickListener(this);
    }

    private void tost(final String str) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(LoginActivity.this, str, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        final String email = mEmailView.getText().toString();
        final String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid preplacedword, if the user entered one.
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError("密码太短");
            focusView = mPreplacedwordView;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError("必须输入");
            focusView = mEmailView;
            cancel = true;
        } else if (!isPhoneValid(email)) {
            mEmailView.setError("手机号格式不对");
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            Http.login(email, preplacedword, new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            showProgress(false);
                            Toast.makeText(getBaseContext(), "网络错误", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    final String body = response.body().string();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            showProgress(false);
                            if (response.code() == 200) {
                                Toast.makeText(getBaseContext(), "登陆成功", Toast.LENGTH_SHORT).show();
                                User user = null;
                                user = JSON.parseObject(body, User.clreplaced);
                                MobclickAgent.onProfileSignIn(user.getPhone());
                                AppApplication.getInstance().setUser(user);
                                new AppPrepare().start(LoginActivity.this, LoginActivity.this);
                            } else {
                                Toast.makeText(getBaseContext(), "手机或密码错误", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            });
        }
    }

    private boolean isPhoneValid(String phone) {
        // TODO: Replace this with your own logic
        return phone.length() == 11 ? true : false;
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.registe) {
            startActivity(new Intent(this, RegisteActivity.clreplaced));
            finish();
        }
    }

    @Override
    public void onPrepared() {
        startActivity(new Intent(this, MainActivity.clreplaced));
        finish();
    }
}

18 Source : DropdownMenuEndIconDelegate.java
with Apache License 2.0
from material-components

private void setPopupBackground(@NonNull AutoCompleteTextView editText) {
    if (IS_LOLLIPOP) {
        int boxBackgroundMode = textInputLayout.getBoxBackgroundMode();
        if (boxBackgroundMode == TextInputLayout.BOX_BACKGROUND_OUTLINE) {
            editText.setDropDownBackgroundDrawable(outlinedPopupBackground);
        } else if (boxBackgroundMode == TextInputLayout.BOX_BACKGROUND_FILLED) {
            editText.setDropDownBackgroundDrawable(filledPopupBackground);
        }
    }
}

18 Source : LoginActivity.java
with MIT License
from llSourcell

/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {

    /**
     * Id to idenreplacedy READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "[email protected]:hello", "[email protected]:world" };

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();
        mPreplacedwordView = (EditText) findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }
        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE).setAction(android.R.string.ok, new View.OnClickListener() {

                @Override
                @TargetApi(Build.VERSION_CODES.M)
                public void onClick(View v) {
                    requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
                }
            });
        } else {
            requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid preplacedword, if the user entered one.
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, preplacedword);
            mAuthTask.execute((Void) null);
            Intent intent = new Intent(this, Payments.clreplaced);
            startActivity(intent);
        }
    }

    private boolean isEmailValid(String email) {
        // TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact.
        Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses.
        ContactsContract.Contacts.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }, // Show primary email addresses first. Note that there won't be
        // a primary email address if the user hasn't specified one.
        ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }
        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        // Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter = new ArrayAdapter<>(LoginActivity.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
        mEmailView.setAdapter(adapter);
    }

    private interface ProfileQuery {

        String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY };

        int ADDRESS = 0;

        int IS_PRIMARY = 1;
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public clreplaced UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;

        private final String mPreplacedword;

        UserLoginTask(String email, String preplacedword) {
            mEmail = email;
            mPreplacedword = preplacedword;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the preplacedword matches.
                    return pieces[1].equals(mPreplacedword);
                }
            }
            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if (success) {
                System.out.println("replaced");
                finish();
            } else {
                mPreplacedwordView.setError(getString(R.string.error_incorrect_preplacedword));
                mPreplacedwordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

18 Source : MainActivity.java
with Apache License 2.0
from liuwan1992

public clreplaced MainActivity extends Activity implements View.OnClickListener {

    private LinearLayout empty;

    private AutoCompleteTextView search;

    private String[] str = { "大大大", "大大小", "大小大", "大小小", "小大大", "小大小", "小大小", "小小小" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        empty = (LinearLayout) findViewById(R.id.empty);
        empty.setOnClickListener(this);
        search = (AutoCompleteTextView) findViewById(R.id.search);
        // 自动提示适配器
        // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, str);
        // 支持拼音检索
        SearchAdapter<String> adapter = new SearchAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, str, SearchAdapter.ALL);
        search.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.empty:
                search.setText("");
                break;
        }
    }
}

18 Source : Sample.java
with Apache License 2.0
from KingsMentor

/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced Sample extends AppCompatActivity implements LoaderCallbacks<Cursor> {

    /**
     * Id to idenreplacedy READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "[email protected]:hello", "[email protected]:world" };

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_manip_sample);
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();
        mPreplacedwordView = (EditText) findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }
        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE).setAction(android.R.string.ok, new View.OnClickListener() {

                @Override
                @TargetApi(Build.VERSION_CODES.M)
                public void onClick(View v) {
                    requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
                }
            });
        } else {
            requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid preplacedword, if the user entered one.
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, preplacedword);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isEmailValid(String email) {
        // TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact.
        Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses.
        ContactsContract.Contacts.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }, // Show primary email addresses first. Note that there won't be
        // a primary email address if the user hasn't specified one.
        ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }
        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        // Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter = new ArrayAdapter<>(Sample.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
        mEmailView.setAdapter(adapter);
    }

    private interface ProfileQuery {

        String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY };

        int ADDRESS = 0;

        int IS_PRIMARY = 1;
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public clreplaced UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;

        private final String mPreplacedword;

        UserLoginTask(String email, String preplacedword) {
            mEmail = email;
            mPreplacedword = preplacedword;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the preplacedword matches.
                    return pieces[1].equals(mPreplacedword);
                }
            }
            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if (success) {
                finish();
            } else {
                mPreplacedwordView.setError(getString(R.string.error_incorrect_preplacedword));
                mPreplacedwordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

18 Source : LoginActivity.java
with MIT License
from kageiit

/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced LoginActivity extends Activity implements LoaderCallbacks<Cursor> {

    /**
     * Id to idenreplacedy READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "[email protected]:hello", "[email protected]:world" };

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mLoginFormView = findViewById(R.id.login_form);
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();
        mPreplacedwordView = (EditText) findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }
        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
        /*Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                    .setAction(android.R.string.ok, new View.OnClickListener() {
                        @Override
                        @TargetApi(Build.VERSION_CODES.M)
                        public void onClick(View v) {
                            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
                        }
                    });*/
        } else {
            requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid preplacedword, if the user entered one.
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, preplacedword);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isEmailValid(String email) {
        // TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact.
        Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses.
        ContactsContract.Contacts.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }, // Show primary email addresses first. Note that there won't be
        // a primary email address if the user hasn't specified one.
        ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }
        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        // Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter = new ArrayAdapter<>(LoginActivity.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
        mEmailView.setAdapter(adapter);
    }

    private interface ProfileQuery {

        String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY };

        int ADDRESS = 0;

        int IS_PRIMARY = 1;
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public clreplaced UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;

        private final String mPreplacedword;

        UserLoginTask(String email, String preplacedword) {
            mEmail = email;
            mPreplacedword = preplacedword;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the preplacedword matches.
                    return pieces[1].equals(mPreplacedword);
                }
            }
            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if (success) {
                finish();
            } else {
                mPreplacedwordView.setError(getString(R.string.error_incorrect_preplacedword));
                mPreplacedwordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

18 Source : InputDialog.java
with GNU General Public License v3.0
from Invinciblelee

/**
 * 输入框
 */
public clreplaced InputDialog extends AppCompatDialog {

    private TextView tvreplacedle;

    private AutoCompleteTextView etInput;

    private TextView tvOk;

    private OnInputOk onInputOk;

    public static void show(FragmentManager fragmentManager, String replacedle, String defValue, OnInputOk onInputOk) {
        InputDialog dialog = new InputDialog();
        Bundle args = new Bundle();
        args.putString("replacedle", replacedle);
        args.putString("defValue", defValue);
        dialog.setArguments(args);
        dialog.onInputOk = onInputOk;
        dialog.show(fragmentManager, "input");
    }

    @Override
    public View onCreateDialogContentView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dialog_input, container, true);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Bundle args = getArguments();
        replacedert args != null;
        final String replacedle = args.getString("replacedle");
        final String defValue = args.getString("defValue");
        tvreplacedle = findViewById(R.id.tv_replacedle);
        etInput = findViewById(R.id.et_input);
        tvOk = findViewById(R.id.tv_ok);
        tvreplacedle.setText(replacedle);
        if (defValue != null) {
            etInput.setText(defValue);
            etInput.setSelectAllOnFocus(true);
        }
        tvOk.setOnClickListener(v -> {
            if (onInputOk != null) {
                onInputOk.setInputText(etInput.getText().toString());
            }
            dismissAllowingStateLoss();
        });
    }

    /**
     * 输入book地址确定
     */
    public interface OnInputOk {

        void setInputText(String inputText);
    }
}

18 Source : AutoCompleteTextViewLayout.java
with Apache License 2.0
from idealclover

/**
 * Created by mnnyang on 17-11-5.
 */
public clreplaced AutoCompleteTextViewLayout extends LinearLayout {

    private AutoCompleteTextView mAtCompTtView;

    private ImageView mIvIcon;

    private ImageView mIvClear;

    private String mHint;

    public AutoCompleteTextViewLayout(Context context) {
        super(context);
        init();
    }

    public AutoCompleteTextViewLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public AutoCompleteTextViewLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.EditTextLayout);
        mHint = typedArray.getString(R.styleable.EditTextLayout_hint);
        String text = typedArray.getString(R.styleable.EditTextLayout_text);
        Drawable icon = typedArray.getDrawable(R.styleable.EditTextLayout_icon);
        Boolean inputEnabled = typedArray.getBoolean(R.styleable.EditTextLayout_input_enabled, true);
        int textColor = typedArray.getColor(R.styleable.EditTextLayout_textColor, Color.BLACK);
        int hintColor = typedArray.getColor(R.styleable.EditTextLayout_hintColor, Color.GRAY);
        typedArray.recycle();
        init();
        setHint(mHint);
        setText(text);
        setIcon(icon);
        setTextColor(textColor);
        setHintColor(hintColor);
        setInputEnabled(inputEnabled);
    }

    private void setHintColor(int color) {
        mAtCompTtView.setHintTextColor(color);
    }

    private void setTextColor(int color) {
        mAtCompTtView.setTextColor(color);
    }

    private void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.layout_custom_auto_complete_text_view, this);
        mAtCompTtView = findViewById(R.id.auto_text_view);
        mIvIcon = findViewById(R.id.iv_icon);
        mIvClear = findViewById(R.id.iv_clear);
        mIvClear.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mAtCompTtView.setText("");
            }
        });
        mAtCompTtView.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                mIvClear.setVisibility(hasFocus ? VISIBLE : INVISIBLE);
                mAtCompTtView.setHint(hasFocus ? "" : mHint);
            }
        });
    }

    /**
     * @param inputType definition of EditorInfo clreplaced
     */
    public AutoCompleteTextViewLayout setInputType(int inputType) {
        mAtCompTtView.setInputType(inputType);
        return this;
    }

    public AutoCompleteTextViewLayout setInputEnabled(boolean enabled) {
        mAtCompTtView.setFocusable(enabled);
        return this;
    }

    public AutoCompleteTextViewLayout setHint(String hint) {
        mHint = hint;
        mAtCompTtView.setHint(hint);
        return this;
    }

    public AutoCompleteTextViewLayout setText(String text) {
        mAtCompTtView.setText(text);
        return this;
    }

    public String getText() {
        return mAtCompTtView.getText().toString();
    }

    public AutoCompleteTextViewLayout setIcon(Drawable icon) {
        if (icon != null) {
            mIvIcon.setImageDrawable(icon);
        }
        return this;
    }

    public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
        mAtCompTtView.setAdapter(adapter);
    }

    @Override
    public void setOnClickListener(@Nullable final OnClickListener l) {
        super.setOnClickListener(l);
        mAtCompTtView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (l != null) {
                    l.onClick(AutoCompleteTextViewLayout.this);
                }
            }
        });
    }

    public void setDropDownVerticalOffset(int offset) {
        mAtCompTtView.setDropDownVerticalOffset(offset);
    }
}

18 Source : LoginActivity.java
with Apache License 2.0
from googlecodelabs

/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced LoginActivity extends AppCompatActivity {

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "[email protected]:hello", "[email protected]:world" };

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = findViewById(R.id.email);
        mPreplacedwordView = findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
        if (!PrefUtils.needsLogin(this)) {
            startActivity(new Intent(this, LoggedInActivity.clreplaced));
            finish();
        }
        overlayDebug((TextView) findViewById(R.id.overlay));
    // ******************* Implement Login Hinting *****************
    // ******************* End implement Login Hinting *************
    }

    private void overlayDebug(@Nullable TextView overlay) {
        if (overlay == null) {
            return;
        }
        overlay.setText(PrefUtils.getDebugText(this));
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        // Show a progress spinner, and kick off a background task to
        // perform the user login attempt.
        showProgress(true);
        mAuthTask = new UserLoginTask(email, preplacedword);
        mAuthTask.execute((Void) null);
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public clreplaced UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;

        private final String mPreplacedword;

        UserLoginTask(String email, String preplacedword) {
            mEmail = email;
            mPreplacedword = preplacedword;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the preplacedword matches.
                    if (pieces[1].equals(mPreplacedword)) {
                        // TODO: register the new account here and get back an authKey
                        return true;
                    }
                }
            }
            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if (success) {
                finishLogin(mEmail, mPreplacedword);
            } else {
                mPreplacedwordView.setError(getString(R.string.error_incorrect_preplacedword));
                mPreplacedwordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }

    private void finishLogin(String email, String preplacedword) {
        // For the sake of this example, we replacedume that the authKey is the preplacedword
        // Note: You should always ensure that usernames/preplacedwords should be excluded
        // from backup for security.
        PrefUtils.setLoginAccount(LoginActivity.this, email, preplacedword);
        startActivity(new Intent(this, LoggedInActivity.clreplaced));
        finish();
    }
}

18 Source : LoginActivity.java
with Apache License 2.0
from googlecodelabs

/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced LoginActivity extends AppCompatActivity {

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "[email protected]:hello", "[email protected]:world" };

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = findViewById(R.id.email);
        mPreplacedwordView = findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
        if (!PrefUtils.needsLogin(this)) {
            startActivity(new Intent(this, LoggedInActivity.clreplaced));
            finish();
        }
        overlayDebug((TextView) findViewById(R.id.overlay));
        // ******************* Implement Login Hinting *****************
        String accountHint = PrefUtils.getLoginHint(this);
        if (accountHint != null) {
            mEmailView.setHint(accountHint);
        }
    // ******************* End implement Login Hinting *************
    }

    private void overlayDebug(@Nullable TextView overlay) {
        if (overlay == null) {
            return;
        }
        overlay.setText(PrefUtils.getDebugText(this));
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        // Show a progress spinner, and kick off a background task to
        // perform the user login attempt.
        showProgress(true);
        mAuthTask = new UserLoginTask(email, preplacedword);
        mAuthTask.execute((Void) null);
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public clreplaced UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;

        private final String mPreplacedword;

        UserLoginTask(String email, String preplacedword) {
            mEmail = email;
            mPreplacedword = preplacedword;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the preplacedword matches.
                    if (pieces[1].equals(mPreplacedword)) {
                        // TODO: register the new account here and get back an authKey
                        return true;
                    }
                }
            }
            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if (success) {
                finishLogin(mEmail, mPreplacedword);
            } else {
                mPreplacedwordView.setError(getString(R.string.error_incorrect_preplacedword));
                mPreplacedwordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }

    private void finishLogin(String email, String preplacedword) {
        // For the sake of this example, we replacedume that the authKey is the preplacedword
        // Note: You should always ensure that usernames/preplacedwords should be excluded
        // from backup for security.
        PrefUtils.setLoginAccount(LoginActivity.this, email, preplacedword);
        startActivity(new Intent(this, LoggedInActivity.clreplaced));
        finish();
    }
}

18 Source : StandardAutoCompleteSignInActivity.java
with Apache License 2.0
from googlearchive

public clreplaced StandardAutoCompleteSignInActivity extends AppCompatActivity {

    private AutoCompleteTextView mUsernameAutoCompleteField;

    private TextView mPreplacedwordField;

    private TextView mLoginButton;

    private TextView mClearButton;

    private boolean mAutofillReceived = false;

    private AutofillManager.AutofillCallback mAutofillCallback;

    private AutofillManager mAutofillManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_with_autocomplete_activity);
        mLoginButton = findViewById(R.id.login);
        mClearButton = findViewById(R.id.clear);
        mUsernameAutoCompleteField = findViewById(R.id.usernameField);
        mPreplacedwordField = findViewById(R.id.preplacedwordField);
        mLoginButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                login();
            }
        });
        mClearButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                AutofillManager afm = getSystemService(AutofillManager.clreplaced);
                if (afm != null) {
                    afm.cancel();
                }
                resetFields();
            }
        });
        mAutofillCallback = new MyAutofillCallback();
        mAutofillManager = getSystemService(AutofillManager.clreplaced);
        ArrayAdapter<CharSequence> mockAutocompleteAdapter = ArrayAdapter.createFromResource(this, R.array.mock_autocomplete_sign_in_suggestions, android.R.layout.simple_dropdown_item_1line);
        mUsernameAutoCompleteField.setAdapter(mockAutocompleteAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mAutofillManager.registerCallback(mAutofillCallback);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mAutofillManager.unregisterCallback(mAutofillCallback);
    }

    private void resetFields() {
        mUsernameAutoCompleteField.setText("");
        mPreplacedwordField.setText("");
    }

    /**
     * Emulates a login action.
     */
    private void login() {
        String username = mUsernameAutoCompleteField.getText().toString();
        String preplacedword = mPreplacedwordField.getText().toString();
        boolean valid = isValidCredentials(username, preplacedword);
        if (valid) {
            Intent intent = WelcomeActivity.getStartActivityIntent(StandardAutoCompleteSignInActivity.this);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "Authentication failed.", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * Dummy implementation for demo purposes. A real service should use secure mechanisms to
     * authenticate users.
     */
    public boolean isValidCredentials(String username, String preplacedword) {
        return username != null && preplacedword != null && username.equals(preplacedword);
    }

    private clreplaced MyAutofillCallback extends AutofillManager.AutofillCallback {

        @Override
        public void onAutofillEvent(@NonNull View view, int event) {
            if (view instanceof AutoCompleteTextView) {
                switch(event) {
                    case AutofillManager.AutofillCallback.EVENT_INPUT_UNAVAILABLE:
                    // no break on purpose
                    case AutofillManager.AutofillCallback.EVENT_INPUT_HIDDEN:
                        if (!mAutofillReceived) {
                            ((AutoCompleteTextView) view).showDropDown();
                        }
                        break;
                    case AutofillManager.AutofillCallback.EVENT_INPUT_SHOWN:
                        mAutofillReceived = true;
                        ((AutoCompleteTextView) view).setAdapter(null);
                        break;
                    default:
                        Log.d(TAG, "Unexpected callback: " + event);
                }
            }
        }
    }
}

18 Source : CallbackLessAutoCompleteSignInActivity.java
with Apache License 2.0
from googlearchive

public clreplaced CallbackLessAutoCompleteSignInActivity extends AppCompatActivity {

    private AutoCompleteTextView mUsernameAutoCompleteField;

    private TextView mPreplacedwordField;

    private TextView mLoginButton;

    private TextView mClearButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_with_autocomplete_activity);
        TextView replacedle = findViewById(R.id.standard_login_header);
        replacedle.setText(R.string.navigation_button_anti_pattern_callbackless_autocomplete_login_label);
        InfoButton info = findViewById(R.id.imageButton);
        info.setInfoText(getString(R.string.anti_pattern_callbackless_autocomplete_login_info));
        mLoginButton = findViewById(R.id.login);
        mClearButton = findViewById(R.id.clear);
        mUsernameAutoCompleteField = findViewById(R.id.usernameField);
        mPreplacedwordField = findViewById(R.id.preplacedwordField);
        mLoginButton.setOnClickListener((v) -> login());
        mClearButton.setOnClickListener((v) -> {
            AutofillManager afm = getSystemService(AutofillManager.clreplaced);
            if (afm != null) {
                afm.cancel();
            }
            resetFields();
        });
        ArrayAdapter<CharSequence> mockAutocompleteAdapter = ArrayAdapter.createFromResource(this, R.array.mock_autocomplete_sign_in_suggestions, android.R.layout.simple_dropdown_item_1line);
        mUsernameAutoCompleteField.setAdapter(mockAutocompleteAdapter);
        mUsernameAutoCompleteField.setThreshold(1);
        // Show it right away
        mUsernameAutoCompleteField.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                mUsernameAutoCompleteField.showDropDown();
            }
        });
    }

    private void resetFields() {
        mUsernameAutoCompleteField.setText("");
        mPreplacedwordField.setText("");
    }

    /**
     * Emulates a login action.
     */
    private void login() {
        String username = mUsernameAutoCompleteField.getText().toString();
        String preplacedword = mPreplacedwordField.getText().toString();
        boolean valid = isValidCredentials(username, preplacedword);
        if (valid) {
            Intent intent = WelcomeActivity.getStartActivityIntent(CallbackLessAutoCompleteSignInActivity.this);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "Authentication failed.", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * Dummy implementation for demo purposes. A real service should use secure mechanisms to
     * authenticate users.
     */
    public boolean isValidCredentials(String username, String preplacedword) {
        return username != null && preplacedword != null && username.equals(preplacedword);
    }
}

18 Source : SimpleInputDialog.java
with Apache License 2.0
from eltos

/**
 * An simple dialog with an input field. Supports suggestions, input validations and
 * max length options.
 *
 * Results:
 *      TEXT    String      The entered text
 *
 * Created by eltos on 14.10.2015.
 */
public clreplaced SimpleInputDialog extends CustomViewDialog<SimpleInputDialog> {

    public static final String TAG = "SimpleInputDialog.";

    public static final String TEXT = TAG + "text";

    public static SimpleInputDialog build() {
        return new SimpleInputDialog();
    }

    /**
     * Sets the EditText's hint
     *
     * @param hint the hint as string
     * @return this instance
     */
    public SimpleInputDialog hint(String hint) {
        return setArg(HINT, hint);
    }

    /**
     * Sets the EditText's hint
     *
     * @param hintResourceId the hint as android string resource
     * @return this instance
     */
    public SimpleInputDialog hint(@StringRes int hintResourceId) {
        return setArg(HINT, hintResourceId);
    }

    /**
     * Sets the EditText's initial text
     *
     * @param text initial text as string
     * @return this instance
     */
    public SimpleInputDialog text(String text) {
        return setArg(TEXT, text);
    }

    /**
     * Sets the EditText's initial text
     *
     * @param textResourceId initial text as android string resource
     * @return this instance
     */
    public SimpleInputDialog text(@StringRes int textResourceId) {
        return setArg(TEXT, textResourceId);
    }

    /**
     * Sets the input type
     * The default is {@link InputType#TYPE_CLreplaced_TEXT}.
     *
     * @param inputType the InputType
     * @return this instance
     */
    public SimpleInputDialog inputType(int inputType) {
        return setArg(INPUT_TYPE, inputType);
    }

    /**
     * Allow empty input. Default is to disable the positive button until text is entered.
     *
     * @param allow whether to allow empty input
     * @return this instance
     */
    public SimpleInputDialog allowEmpty(boolean allow) {
        return setArg(ALLOW_EMPTY, allow);
    }

    /**
     * Sets a max limit to the EditText.
     *
     * @param maxLength the maximum text length
     * @return this instance
     */
    public SimpleInputDialog max(int maxLength) {
        return setArg(MAX_LENGTH, maxLength);
    }

    /**
     * Provide an array of suggestions to be shown while the user is typing
     *
     * @param context a context to resolve the resource ids
     * @param stringResourceIds suggestion array as android string resources
     * @return this instance
     */
    public SimpleInputDialog suggest(Context context, int[] stringResourceIds) {
        String[] strings = new String[stringResourceIds.length];
        for (int i = 0; i < stringResourceIds.length; i++) {
            strings[i] = context.getString(stringResourceIds[i]);
        }
        return suggest(strings);
    }

    /**
     * Provide an array of suggestions to be shown while the user is typing
     *
     * @param strings suggestion string array
     * @return this instance
     */
    public SimpleInputDialog suggest(String[] strings) {
        getArguments().putStringArray(SUGGESTIONS, strings);
        return this;
    }

    public interface InputValidator {

        /**
         * Let the hosting fragment or activity implement this interface to control
         * when a user can proceed or to display an error message on an invalid input.
         * The method is called every time the user hits the positive button
         *
         * @param dialogTag the tag of this fragment
         * @param input the text entered by the user
         * @param extras the extras preplaceded with {@link SimpleInputDialog#extra(Bundle)}
         * @return an error message to display or null if the input is valid
         */
        String validate(String dialogTag, @Nullable String input, @NonNull Bundle extras);
    }

    protected static final String HINT = TAG + "hint", INPUT_TYPE = TAG + "input_type", ALLOW_EMPTY = TAG + "allow_empty", MAX_LENGTH = TAG + "max_length", SUGGESTIONS = TAG + "suggestions";

    private AutoCompleteTextView mInput;

    private TextInputLayout mInputLayout;

    protected String onValidateInput(@Nullable String input) {
        Bundle extras = getExtras();
        if (getTargetFragment() instanceof InputValidator) {
            return ((InputValidator) getTargetFragment()).validate(getTag(), input, extras);
        }
        if (getActivity() instanceof InputValidator) {
            return ((InputValidator) getActivity()).validate(getTag(), input, extras);
        }
        return null;
    }

    /**
     * @return the current text or null
     */
    @Nullable
    public String getText() {
        return mInput.getText() != null ? mInput.getText().toString() : null;
    }

    public boolean isInputEmpty() {
        return getText() == null || getText().trim().isEmpty();
    }

    /**
     * Helper for opening the soft keyboard
     */
    public void openKeyboard() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(mInput, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    @Override
    public View onCreateContentView(Bundle savedInstanceState) {
        // inflate and set your custom view here
        View view = inflate(R.layout.simpledialogfragment_input);
        mInput = (AutoCompleteTextView) view.findViewById(R.id.editText);
        mInputLayout = (TextInputLayout) view.findViewById(R.id.inputLayout);
        // Note: setting TYPE_CLreplaced_TEXT as default is very important!
        mInput.setInputType(getArguments().getInt(INPUT_TYPE, InputType.TYPE_CLreplaced_TEXT));
        if ((getArguments().getInt(INPUT_TYPE) & InputType.TYPE_MASK_CLreplaced) == InputType.TYPE_CLreplaced_PHONE) {
            // format phone number automatically
            mInput.addTextChangedListener(new PhoneNumberFormattingTexreplacedcher());
        }
        // mInput.setHint(getArgString(HINT));
        mInputLayout.setHint(getArgString(HINT));
        if (getArguments().getInt(MAX_LENGTH) > 0) {
            mInputLayout.setCounterMaxLength(getArguments().getInt(MAX_LENGTH));
            mInputLayout.setCounterEnabled(true);
        }
        if (savedInstanceState != null) {
            mInput.setText(savedInstanceState.getString(TEXT));
        } else {
            mInput.setText(getArgString(TEXT));
            mInput.setSelection(0, mInput.length());
        }
        mInput.setImeOptions(EditorInfo.IME_ACTION_DONE);
        mInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    pressPositiveButton();
                    return true;
                }
                return false;
            }
        });
        mInput.addTextChangedListener(new Texreplacedcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                setPositiveButtonEnabled(posEnabled());
            }
        });
        // Auto complete
        String[] suggestionList = getArguments().getStringArray(SUGGESTIONS);
        if (suggestionList != null) {
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), // android.R.layout.simple_dropdown_item_1line
            android.R.layout.simple_list_item_1, suggestionList);
            mInput.setAdapter(adapter);
            mInput.setThreshold(1);
        }
        return view;
    }

    protected boolean posEnabled() {
        return (!isInputEmpty() || getArguments().getBoolean(ALLOW_EMPTY)) && (getText() == null || getText().length() <= getArguments().getInt(MAX_LENGTH, getText().length()));
    }

    @Override
    protected void onDialogShown() {
        setPositiveButtonEnabled(posEnabled());
        // mInput.requestFocus();
        openKeyboard();
    }

    @Override
    protected boolean acceptsPositiveButtonPress() {
        String input = getText();
        String error = onValidateInput(input);
        if (error == null) {
            return true;
        } else {
            mInputLayout.setError(error);
            mInputLayout.setErrorEnabled(true);
            return false;
        }
    }

    @Override
    public Bundle onResult(int which) {
        Bundle result = new Bundle();
        result.putString(TEXT, getText());
        return result;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(TEXT, getText());
    }
}

18 Source : DropdownMenuEndIconDelegate.java
with Apache License 2.0
from covidsafewatch

/* access modifiers changed from: private */
public void setPopupBackground(AutoCompleteTextView autoCompleteTextView) {
    if (IS_LOLLIPOP) {
        int boxBackgroundMode = this.textInputLayout.getBoxBackgroundMode();
        if (boxBackgroundMode == 2) {
            autoCompleteTextView.setDropDownBackgroundDrawable(this.outlinedPopupBackground);
        } else if (boxBackgroundMode == 1) {
            autoCompleteTextView.setDropDownBackgroundDrawable(this.filledPopupBackground);
        }
    }
}

18 Source : DropdownMenuEndIconDelegate.java
with Apache License 2.0
from covidsafewatch

/* access modifiers changed from: private */
public void setUpDropdownShowHideBehavior(final AutoCompleteTextView autoCompleteTextView) {
    autoCompleteTextView.setOnTouchListener(new View.OnTouchListener() {

        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == 1) {
                if (DropdownMenuEndIconDelegate.this.isDropdownPopupActive()) {
                    boolean unused = DropdownMenuEndIconDelegate.this.dropdownPopupDirty = false;
                }
                DropdownMenuEndIconDelegate.this.showHideDropdown(autoCompleteTextView);
                view.performClick();
            }
            return false;
        }
    });
    autoCompleteTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        public void onFocusChange(View view, boolean z) {
            DropdownMenuEndIconDelegate.this.textInputLayout.setEndIconActivated(z);
            if (!z) {
                DropdownMenuEndIconDelegate.this.setEndIconChecked(false);
                boolean unused = DropdownMenuEndIconDelegate.this.dropdownPopupDirty = false;
            }
        }
    });
    if (IS_LOLLIPOP) {
        autoCompleteTextView.setOnDismissListener(new AutoCompleteTextView.OnDismissListener() {

            public void onDismiss() {
                boolean unused = DropdownMenuEndIconDelegate.this.dropdownPopupDirty = true;
                long unused2 = DropdownMenuEndIconDelegate.this.dropdownPopupActivatedAt = System.currentTimeMillis();
                DropdownMenuEndIconDelegate.this.setEndIconChecked(false);
            }
        });
    }
}

18 Source : AutoCompleteEditTextWrapper.java
with Apache License 2.0
from AnywhereSoftware

/**
 * Forces the drop down list to disappear.
 */
public void DismissDropDown() {
    AutoCompleteTextView a = (AutoCompleteTextView) getObject();
    a.dismissDropDown();
}

18 Source : AutoCompleteEditTextWrapper.java
with Apache License 2.0
from AnywhereSoftware

@Hide
public static View build(Object prev, HashMap<String, Object> props, boolean designer, Object tag) throws Exception {
    AutoCompleteTextView v;
    if (prev == null) {
        v = ViewWrapper.buildNativeView((Context) tag, AutoCompleteTextView.clreplaced, props, designer);
    } else
        v = (AutoCompleteTextView) prev;
    return EditTextWrapper.build(v, props, designer, tag);
}

18 Source : LoginActivityB.java
with GNU General Public License v3.0
from analysys

/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced LoginActivityB extends AppCompatActivity implements LoaderCallbacks<Cursor> {

    /**
     * Id to idenreplacedy READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "[email protected]:hello", "[email protected]:world" };

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_activity);
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();
        mPreplacedwordView = (EditText) findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }
        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE).setAction(android.R.string.ok, new OnClickListener() {

                @Override
                @TargetApi(Build.VERSION_CODES.M)
                public void onClick(View v) {
                    requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
                }
            });
        } else {
            requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid preplacedword, if the user entered one.
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, preplacedword);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isEmailValid(String email) {
        // TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact.
        Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses.
        ContactsContract.Contacts.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }, // Show primary email addresses first. Note that there won't be
        // a primary email address if the user hasn't specified one.
        ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }
        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        // Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter = new ArrayAdapter<>(LoginActivityB.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
        mEmailView.setAdapter(adapter);
    }

    private interface ProfileQuery {

        String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY };

        int ADDRESS = 0;

        int IS_PRIMARY = 1;
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public clreplaced UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;

        private final String mPreplacedword;

        UserLoginTask(String email, String preplacedword) {
            mEmail = email;
            mPreplacedword = preplacedword;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the preplacedword matches.
                    return pieces[1].equals(mPreplacedword);
                }
            }
            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if (success) {
                finish();
            } else {
                mPreplacedwordView.setError(getString(R.string.error_incorrect_preplacedword));
                mPreplacedwordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

18 Source : LoginActivityA.java
with GNU General Public License v3.0
from analysys

/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced LoginActivityA extends AppCompatActivity implements LoaderCallbacks<Cursor> {

    /**
     * Id to idenreplacedy READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "[email protected]:hello", "[email protected]:world" };

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_activity);
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();
        mPreplacedwordView = (EditText) findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }
        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE).setAction(android.R.string.ok, new View.OnClickListener() {

                @Override
                @TargetApi(Build.VERSION_CODES.M)
                public void onClick(View v) {
                    requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
                }
            });
        } else {
            requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid preplacedword, if the user entered one.
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, preplacedword);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isEmailValid(String email) {
        // TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact.
        Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses.
        ContactsContract.Contacts.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }, // Show primary email addresses first. Note that there won't be
        // a primary email address if the user hasn't specified one.
        ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }
        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        // Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter = new ArrayAdapter<>(LoginActivityA.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
        mEmailView.setAdapter(adapter);
    }

    private interface ProfileQuery {

        String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY };

        int ADDRESS = 0;

        int IS_PRIMARY = 1;
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public clreplaced UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;

        private final String mPreplacedword;

        UserLoginTask(String email, String preplacedword) {
            mEmail = email;
            mPreplacedword = preplacedword;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the preplacedword matches.
                    return pieces[1].equals(mPreplacedword);
                }
            }
            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if (success) {
                finish();
            } else {
                mPreplacedwordView.setError(getString(R.string.error_incorrect_preplacedword));
                mPreplacedwordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

18 Source : ChipLayout.java
with Apache License 2.0
from AmaldevTA

public void setAdapter(ArrayAdapter adapter) {
    this.adapter = adapter;
    if (this.getChildCount() > 0) {
        AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) ((ViewGroup) this.getChildAt(this.getChildCount() - 1)).getChildAt(labelPosition);
        autoCompleteTextView.setAdapter(adapter);
    }
}

18 Source : ChipLayout.java
with Apache License 2.0
from AmaldevTA

public void setHint(String hint) {
    hintText = hint;
    if (this.getChildCount() == 1) {
        AutoCompleteTextView textView = (AutoCompleteTextView) this.getChildAt(0).findViewWithTag(autoCompleteTextViewTag);
        textView.setHint(hintText);
    }
}

18 Source : ChipLayout.java
with Apache License 2.0
from AmaldevTA

public void setTextColor(int textColor) {
    this.textColor = textColor;
    for (int i = 0; i < this.getChildCount(); i++) {
        AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) ((ViewGroup) this.getChildAt(i)).getChildAt(labelPosition);
        autoCompleteTextView.setTextColor(textColor);
        ((ChipTexreplacedcher) focusedTexreplacedcher).setTextColor(textColor);
    }
}

18 Source : ChipLayout.java
with Apache License 2.0
from AmaldevTA

public void removeChipAt(int pos) {
    AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) ((ViewGroup) this.getChildAt(pos)).getChildAt(labelPosition);
    this.removeViewAt(pos);
    if (chipItemChangeListener != null) {
        if (autoCompleteTextView.getText() != null && autoCompleteTextView.getText().toString().length() > 0) {
            chipItemChangeListener.onChipRemoved(pos, autoCompleteTextView.getText().toString());
        } else {
            chipItemChangeListener.onChipRemoved(pos, "");
        }
    }
    setHint(hintText);
}

18 Source : LoginActivity.java
with Apache License 2.0
from AllanHasegawa

/**
 * A login screen that offers login via username/preplacedword.
 */
public clreplaced LoginActivity extends AppCompatActivity {

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "me:123:token9", "yo:hunter2:token2" };

    private AutoCompleteTextView usernameActv;

    private EditText preplacedwordEt;

    private TextView errorTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        usernameActv = (AutoCompleteTextView) findViewById(R.id.login_username_actv);
        preplacedwordEt = (EditText) findViewById(R.id.login_preplacedword_et);
        preplacedwordEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        errorTv = (TextView) findViewById(R.id.login_error_tv);
        Button usernameSignInButton = (Button) findViewById(R.id.login_sign_in_bt);
        usernameSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
    }

    private void attemptLogin() {
        errorTv.setVisibility(View.GONE);
        String username = usernameActv.getText().toString();
        String preplacedword = preplacedwordEt.getText().toString();
        for (String credential : DUMMY_CREDENTIALS) {
            String[] split = credential.split(":");
            if (username.equals(split[0]) && preplacedword.equals(split[1])) {
                String token = split[2];
                FavoritesActivity.launch(this, token, false);
                return;
            }
        }
        errorTv.setVisibility(View.VISIBLE);
    }
}

17 Source : LoginActivity.java
with Apache License 2.0
from yifei8

/**
 * A login screen that offers login via email/preplacedword.
 */
@Route(path = "/login-module/LoginActivity")
public clreplaced LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {

    /**
     * Id to idenreplacedy READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "[email protected]:hello", "[email protected]:world" };

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();
        mPreplacedwordView = (EditText) findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }
        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE).setAction(android.R.string.ok, new View.OnClickListener() {

                @Override
                @TargetApi(Build.VERSION_CODES.M)
                public void onClick(View v) {
                    requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
                }
            });
        } else {
            requestPermissions(new String[] { READ_CONTACTS }, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid preplacedword, if the user entered one.
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, preplacedword);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isEmailValid(String email) {
        // TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact.
        Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses.
        ContactsContract.Contacts.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }, // Show primary email addresses first. Note that there won't be
        // a primary email address if the user hasn't specified one.
        ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }
        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        // Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter = new ArrayAdapter<>(LoginActivity.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
        mEmailView.setAdapter(adapter);
    }

    private interface ProfileQuery {

        String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY };

        int ADDRESS = 0;

        int IS_PRIMARY = 1;
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public clreplaced UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;

        private final String mPreplacedword;

        UserLoginTask(String email, String preplacedword) {
            mEmail = email;
            mPreplacedword = preplacedword;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the preplacedword matches.
                    return pieces[1].equals(mPreplacedword);
                }
            }
            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if (success) {
                Routerfit.setResult(Routerfit.RESULT_OK, "result from LoginActivity");
                finish();
            } else {
                mPreplacedwordView.setError(getString(R.string.error_incorrect_preplacedword));
                mPreplacedwordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

17 Source : LoginActivity.java
with Apache License 2.0
from whisper90

/**
 * A login screen that offers login via email/preplacedword.
 */
public clreplaced LoginActivity extends AppCompatActivity {

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    private void saveNext() {
        try {
            if (mEmailView.getText().toString().length() != 11) {
                return;
            }
            List<AccountEnreplacedy> mList = JsonUtils.listJson((String) SPUtils.getString(ACCOUNT_LIST, "-1"), AccountEnreplacedy.clreplaced);
            if (mList == null) {
                mList = new ArrayList<>();
            }
            AccountEnreplacedy mAccountEnreplacedy = new AccountEnreplacedy();
            mAccountEnreplacedy.setAccount(mEmailView.getText().toString());
            mAccountEnreplacedy.setPreplacedword(mPreplacedwordView.getText().toString());
            mList.add(mAccountEnreplacedy);
            SPUtils.save(Constants.ACCOUNT_LIST, JsonUtils.toJson(mList));
            DingHelperUtils.setAlarm(mAccountEnreplacedy, App.mContext);
            mEmailView.setText("");
            mPreplacedwordView.setText("");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private ProgressDialog mProgressDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mProgressDialog = new ProgressDialog(this);
        this.findViewById(R.id.account_save_button).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                saveNext();
            }
        });
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        mPreplacedwordView = (EditText) findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid preplacedword, if the user entered one.
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            /*showProgress(true);
            mAuthTask = new UserLoginTask(email, preplacedword);
            mAuthTask.execute((Void) null);*/
            /*SPUtils.put(App.mContext, Constants.IS_SIGN, true);
            SPUtils.put(App.mContext, Constants.ACCOUNT, email);
            SPUtils.put(App.mContext, Constants.PreplacedWORD, preplacedword);
            SPUtils.put(App.mContext, Constants.DATE, mTimeTextView.getText().toString());*/
            if (mEmailView.getText().toString().length() != 11) {
                Toast.makeText(App.mContext, "钉钉账号必须为手机账户,长度为11", Toast.LENGTH_SHORT).show();
                return;
            }
            mProgressDialog.show();
            saveNext();
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {

                @Override
                public void run() {
                    try {
                        mProgressDialog.dismiss();
                        LoginActivity.this.setResult(RESULT_OK);
                        LoginActivity.this.finish();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, 500);
        }
    }

    private boolean isEmailValid(String email) {
        // TODO: Replace this with your own logic
        return true;
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }
}

17 Source : CreateTribeActivity.java
with GNU General Public License v3.0
from TudorCretu

public clreplaced CreateTribeActivity extends AppCompatActivity {

    private String mUID;

    private AutoCompleteTextView tribeNameView;

    private Button doneButton;

    private DatabaseReference mDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_tribe);
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, SUGGESTEDNAMES);
        tribeNameView = (AutoCompleteTextView) findViewById(R.id.create_tribe_et);
        tribeNameView.setMaxLines(1);
        tribeNameView.setInputType(InputType.TYPE_CLreplaced_TEXT);
        tribeNameView.setAdapter(adapter);
        imm.showSoftInput(tribeNameView, InputMethodManager.SHOW_IMPLICIT);
        doneButton = (Button) findViewById(R.id.create_tribe_done);
        doneButton.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View create_tribe_done) {
                String tribeName = (String) tribeNameView.getText().toString();
                if (tribeName.matches("")) {
                    Toast.makeText(CreateTribeActivity.this, "You did not enter the name of your tribe", Toast.LENGTH_SHORT).show();
                } else {
                    // create token for tribe
                    mUID = FirebaseAuth.getInstance().getCurrentUser().getUid();
                    mLastTribeUID = (String) UUID.randomUUID().toString();
                    mDatabase = FirebaseDatabase.getInstance().getReference();
                    mDatabase.child("tribes").child(mLastTribeUID).child("UID").setValue(mLastTribeUID);
                    mDatabase.child("tribes").child(mLastTribeUID).child("name").setValue(tribeName);
                    mDatabase.child("tribes").child(mLastTribeUID).child("timestamp").setValue(new Date().getTime());
                    mDatabase.child("tribes").child(mLastTribeUID).child("members").child(mUID).setValue(true);
                    mDatabase.child("tribes").child(mLastTribeUID).child("inviteCode").setValue("a");
                    mDatabase.child("tribes").child(mLastTribeUID).child("validUntil").setValue(1);
                    mDatabase.child("users").child(mUID).child("tribes").child(mLastTribeUID).child("name").setValue(tribeName);
                    mDatabase.child("users").child(mUID).child("lastTribe").setValue(mLastTribeUID);
                    Intent intent = new Intent(CreateTribeActivity.this, InviteActivity.clreplaced);
                    startActivity(intent);
                    finish();
                }
            }
        });
        tribeNameView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    doneButton.performClick();
                    return true;
                }
                return false;
            }
        });
    }

    private static final String[] SUGGESTEDNAMES = new String[] { "Family", "Friends", "Siblings", "Extended Familiy", "Special Someone", "Significant Other", "Field Trip Group", "Carpool", "Vacation Group", "Babysitter", "Coworkers", "Lunch Friends" };
}

17 Source : ViewUtils.java
with GNU General Public License v2.0
from theo-jedi

public static void updateFilterDropdown(Context context, AutoCompleteTextView view, List<String> hints) {
    ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, hints);
    view.setAdapter(adapter);
    view.dismissDropDown();
}

17 Source : DictionaryActivity.java
with GNU General Public License v2.0
from theo-jedi

public void disableDictionaryInputs(EditText editText, AutoCompleteTextView autoCompleteTextView) {
    ViewUtils.disbaleInput(editText);
    ViewUtils.disbaleInput(autoCompleteTextView);
    ViewUtils.updateDropdown(this, autoCompleteTextView, keywordTypes);
}

17 Source : LoginActivity.java
with Apache License 2.0
from Tamicer

/**
 * A login screen that offers login via email/preplacedword.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public clreplaced LoginActivity extends TamicActivity implements LoaderCallbacks<Cursor> {

    /**
     * Id to idenreplacedy READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and preplacedwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "[email protected]:hello", "[email protected]:world" };

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @TargetApi(Build.VERSION_CODES.CUPCAKE)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        // populateAutoComplete();
        mPreplacedwordView = (EditText) findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }
        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        /* if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                    .setAction(android.R.string.ok, new View.OnClickListener() {
                        @Override
                        @TargetApi(Build.VERSION_CODES.M)
                        public void onClick(View v) {
                            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
                        }
                    });
        } else {
            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
        }*/
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid preplacedword, if the user entered one.
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, preplacedword);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isEmailValid(String email) {
        // TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact.
        Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses.
        ContactsContract.Contacts.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }, // Show primary email addresses first. Note that there won't be
        // a primary email address if the user hasn't specified one.
        ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }
        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
    }

    private interface ProfileQuery {

        String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY };

        int ADDRESS = 0;

        int IS_PRIMARY = 1;
    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        // Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter = new ArrayAdapter<>(LoginActivity.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
        mEmailView.setAdapter(adapter);
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public clreplaced UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;

        private final String mPreplacedword;

        UserLoginTask(String email, String preplacedword) {
            mEmail = email;
            mPreplacedword = preplacedword;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the preplacedword matches.
                    return pieces[1].equals(mPreplacedword);
                }
            }
            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);
            if (success) {
                finish();
            } else {
                mPreplacedwordView.setError(getString(R.string.error_incorrect_preplacedword));
                mPreplacedwordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

17 Source : LoginActivity.java
with Apache License 2.0
from Tamicer

/**
 * A login screen that offers login via email/preplacedword.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public clreplaced LoginActivity extends ModelActivity<LoginContract.View, LoginPresenter> implements LoginContract.View {

    /**
     * Id to idenreplacedy READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    // UI references.
    private AutoCompleteTextView mEmailView;

    private EditText mPreplacedwordView;

    private View mProgressView;

    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        mPreplacedwordView = (EditText) findViewById(R.id.preplacedword);
        mPreplacedwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        // Reset errors.
        mEmailView.setError(null);
        mPreplacedwordView.setError(null);
        // Store values at the time of the login attempt.
        final String email = mEmailView.getText().toString();
        final String preplacedword = mPreplacedwordView.getText().toString();
        boolean cancel = false;
        View focusView = null;
        // Check for a valid preplacedword, if the user entered one.
        if (!TextUtils.isEmpty(preplacedword) && !isPreplacedwordValid(preplacedword)) {
            mPreplacedwordView.setError(getString(R.string.error_invalid_preplacedword));
            focusView = mPreplacedwordView;
            cancel = true;
        }
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            focusView.requestFocus();
        } else {
            presenter.login(new CallBack<UserBean>() {

                @Override
                public void onSuccess(int code, String msg, UserBean data) {
                    showToast(data.getData().getCountry());
                }

                @Override
                public void onFailure(int code, String msg) {
                    showToast(msg);
                }
            }, email, preplacedword);
            presenter.start();
        /* By  Rxjava
                    presenter.login(email, preplacedword)
                    .subscribeOn(Schedulers.newThread())
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<UserBean>() {

                        @Override
                        public void accept(UserBean userBean) throws Exception {
                            if(userBean != null) {
                                showToast(userBean.getData().getCity());
                                showUIProgress(false);
                            }
                        }
                    });*/
        }
    }

    private boolean isEmailValid(String email) {
        // TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPreplacedwordValid(String preplacedword) {
        // TODO: Replace this with your own logic
        return preplacedword.length() > 4;
    }

    private void showToast(final String data) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(LoginActivity.this, data, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showUIProgress(final boolean show) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                showProgress(show);
            }
        });
    }

    private void resfreshUI(final String content) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                mPreplacedwordView.setError(content);
                mPreplacedwordView.requestFocus();
            }
        });
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public void showLoading() {
        showUIProgress(true);
    }

    @Override
    public void dismissLoading() {
        showUIProgress(false);
    }

    @Override
    public void setPresenter(IPresenter presenter) {
        this.presenter = (LoginPresenter) presenter;
    }
}

See More Examples