Example usage for android.view KeyEvent KEYCODE_ENTER

List of usage examples for android.view KeyEvent KEYCODE_ENTER

Introduction

In this page you can find the example usage for android.view KeyEvent KEYCODE_ENTER.

Prototype

int KEYCODE_ENTER

To view the source code for android.view KeyEvent KEYCODE_ENTER.

Click Source Link

Document

Key code constant: Enter key.

Usage

From source file:org.profeda.dictionary.SearchActivity.java

/**
 * Called when the activity is first created.
 *///  w  w  w . j  a v a 2s  .com
@Override
public void onCreate(Bundle savedInstanceState) {
    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(SearchActivity.this);

    if (pref.getBoolean("show_changelog", true) == true) {
        MessageBox.showChangeLog(this);
    }

    loadDictionaries(pref);

    if (pref.getBoolean("p_invert_colors", false) == true) {
        setTheme(R.style.Light);
    } else {
        setTheme(R.style.Dark);
    }

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    dict = new Dict(this, pref.getString("dictFile", null));

    updateTitleBar();
    readMRU();

    final EditText searchbox = (EditText) findViewById(R.id.searchbox);
    final Button dictselectbutton = (Button) findViewById(R.id.dictselectbutton);
    final ListView listview = (ListView) findViewById(R.id.contentlist);

    listview.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView l, View v, int position, long id) {
            ListAdapter la = ((ListView) l).getAdapter();
            if (la instanceof GenericStringAdapter) {
                final String data = (String) la.getItem(position);
                if (data.startsWith("> ")) {
                    searchbox.setText(data.substring(2));
                    doSearch(true);
                }
            } else if (la instanceof DictListAdapter) {
                final String[] data = (String[]) la.getItem(position);

                final List<Dict> langs = Dict.searchForLanguage(SearchActivity.this, dict.toLang, null);

                String[] menu = new String[langs.size() + 1];
                menu[0] = getString(R.string.copy_translation_to_clipboard);
                for (int i = 1; i < menu.length; i++)
                    menu[i] = String.format(getString(R.string.search_translation_in_language),
                            langs.get(i - 1).toLang);

                Matcher m = Pattern.compile("<b>(.*)<\\/b>.*").matcher(data[1]);
                if (!m.matches())
                    return;
                final String translation = m.group(1).trim();

                new AlertDialog.Builder(SearchActivity.this).setIcon(android.R.drawable.ic_dialog_info)
                        .setTitle(translation).setItems(menu, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                switch (arg1) {
                                case 0:
                                    ClipboardManager cm = (ClipboardManager) getSystemService(
                                            CLIPBOARD_SERVICE);
                                    cm.setText(translation);
                                    break;
                                default:
                                    dict = langs.get(arg1 - 1);
                                    readMRU();
                                    updateTitleBar();
                                    searchbox.setText(translation);
                                    doSearch(true);
                                }
                            }
                        }).show();
            }
        }
    });

    searchbox.setOnEditorActionListener(new EditText.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE
                    || event.getAction() == KeyEvent.ACTION_DOWN
                            && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                doSearch(true);
                return true;
            } else {
                return false;
            }
        }
    });

    final Drawable deleteIcon = getResources().getDrawable(R.drawable.textbox_clear);
    //deleteIcon.setBounds(0, 0, deleteIcon.getIntrinsicWidth(), deleteIcon.getIntrinsicHeight());
    deleteIcon.setBounds(0, 0, 51, 30); // wtf??? die Zahlen sind empirisch ermittelt... ab right>=52 springt die hhe des editText

    searchbox.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            searchbox.setCompoundDrawables(null, null, s.toString().equals("") ? null : deleteIcon, null);
            //searchbox.setCompoundDrawablesWithIntrinsicBounds(null, null, s.toString().equals("") ? null : deleteIcon, null);
            searchbox.setCompoundDrawablePadding(0);
        }

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

        @Override
        public void afterTextChanged(Editable s) {
            if (enableLivesearch && s.length() > 1 && dict.filePrefix != null && dictSearchInAction == false) {
                DictionarySearcher ds = new DictionarySearcher();
                ds.targetList = (ListView) findViewById(R.id.contentlist);
                ds.execute(dict.filePrefix, s.toString());
            }
            if (s.length() == 0) {
                displayMRU();
            }
        }
    });

    //searchbox.setCompoundDrawables(null, null, deleteIcon, null);
    searchbox.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (searchbox.getCompoundDrawables()[2] == null) {
                return false;
            }
            if (event.getAction() != MotionEvent.ACTION_UP) {
                return false;
            }
            if (event.getX() > searchbox.getWidth() - searchbox.getPaddingRight()
                    - deleteIcon.getIntrinsicWidth()) {
                searchbox.setText("");
                searchbox.setCompoundDrawables(null, null, null, null);
            }
            return false;
        }
    });

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

    ((Button) findViewById(R.id.dictswapbutton)).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            final List<Dict> langs = Dict.searchForLanguage(SearchActivity.this, dict.toLang, dict.fromLang);
            if (langs.size() > 0) {
                dict = langs.get(0);
                readMRU();
                updateTitleBar();
                searchbox.setText("");
            } else {
                MessageBox.alert(SearchActivity.this, getString(R.string.no_reverse_dict_found));
            }
        }
    });

}

From source file:br.ufrgs.ufrgsmapas.libs.SearchBox.java

/**
 * Create a searchbox with params and a style
 * @param context Context/*from www  .j  a v  a  2s  . co  m*/
 * @param attrs Attributes
 * @param defStyle Style
 */
public SearchBox(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    inflate(context, R.layout.searchbox, this);
    this.searchOpen = false;
    this.isMic = true;
    this.materialMenu = (MaterialMenuView) findViewById(R.id.material_menu_button);
    this.logo = (TextView) findViewById(R.id.logo);
    this.search = (EditText) findViewById(R.id.search);
    this.results = (ListView) findViewById(R.id.results);
    this.context = context;
    this.pb = (ProgressBar) findViewById(R.id.pb);
    this.mic = (ImageView) findViewById(R.id.mic);
    this.drawerLogo = (ImageView) findViewById(R.id.drawer_logo);

    mCollator = Collator.getInstance(new Locale("pt", "BR"));
    mCollator.setStrength(Collator.PRIMARY);

    materialMenu.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (searchOpen) {
                toggleSearch();
            } else {
                if (menuListener != null)
                    menuListener.onMenuClick();
            }
        }

    });
    resultList = new ArrayList<SearchResult>();
    results.setAdapter(new SearchAdapter(context, resultList));
    animate = true;
    isVoiceRecognitionIntentSupported = isIntentAvailable(context,
            new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
    logo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            toggleSearch();
        }

    });
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        RelativeLayout searchRoot = (RelativeLayout) findViewById(R.id.search_root);
        LayoutTransition lt = new LayoutTransition();
        lt.setDuration(100);
        searchRoot.setLayoutTransition(lt);
    }
    searchables = new ArrayList<SearchResult>();
    search.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                search(getSearchText());
                return true;
            }
            return false;
        }
    });
    search.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                if (TextUtils.isEmpty(getSearchText())) {
                    toggleSearch();
                } else {
                    search(getSearchText());
                }
                return true;
            }
            return false;
        }
    });
    logoText = "Logo";
    micStateChanged();
    mic.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (voiceRecognitionListener != null) {
                voiceRecognitionListener.onClick();
            } else {
                micClick();
            }
        }
    });
}

From source file:org.sipdroid.sipua.ui.Sipdroid.java

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.sipdroid);//w  w  w  .java2  s.c o  m
    sip_uri_box = (AutoCompleteTextView) findViewById(R.id.txt_callee);
    sip_uri_box2 = (AutoCompleteTextView) findViewById(R.id.txt_callee2);
    sip_uri_box.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                call_menu(sip_uri_box);
                return true;
            }
            return false;
        }
    });
    sip_uri_box.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            call_menu(sip_uri_box);
        }
    });
    sip_uri_box2.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                call_menu(sip_uri_box2);
                return true;
            }
            return false;
        }
    });
    sip_uri_box2.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            call_menu(sip_uri_box2);
        }
    });
    on(this, true);

    Button contactsButton = (Button) findViewById(R.id.contacts_button);
    contactsButton.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            Intent myIntent = new Intent(Intent.ACTION_DIAL);
            startActivity(myIntent);
        }
    });

    final Context mContext = this;

    Button settingsButton = (Button) findViewById(R.id.settings_button);
    settingsButton.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            Intent myIntent = new Intent(mContext, org.sipdroid.sipua.ui.Settings.class);
            startActivity(myIntent);
        }
    });

    final OnDismissListener listener = this;

    createButton = (Button) findViewById(R.id.create_button);
    createButton.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            CreateAccount createDialog = new CreateAccount(mContext);
            createDialog.setOnDismissListener(listener);
            createDialog.show();
        }
    });

    if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Settings.PREF_NOPORT,
            Settings.DEFAULT_NOPORT)) {
        boolean ask = false;
        for (int i = 0; i < SipdroidEngine.LINES; i++) {
            String j = (i != 0 ? "" + i : "");
            if (PreferenceManager.getDefaultSharedPreferences(this)
                    .getString(Settings.PREF_SERVER + j, Settings.DEFAULT_SERVER)
                    .equals(Settings.DEFAULT_SERVER)
                    && PreferenceManager.getDefaultSharedPreferences(this)
                            .getString(Settings.PREF_USERNAME + j, Settings.DEFAULT_USERNAME).length() != 0
                    && PreferenceManager.getDefaultSharedPreferences(this)
                            .getString(Settings.PREF_PORT + j, Settings.DEFAULT_PORT)
                            .equals(Settings.DEFAULT_PORT))
                ask = true;
        }
        if (ask)
            new AlertDialog.Builder(this).setMessage(R.string.dialog_port)
                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            Editor edit = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
                            for (int i = 0; i < SipdroidEngine.LINES; i++) {
                                String j = (i != 0 ? "" + i : "");
                                if (PreferenceManager.getDefaultSharedPreferences(mContext)
                                        .getString(Settings.PREF_SERVER + j, Settings.DEFAULT_SERVER)
                                        .equals(Settings.DEFAULT_SERVER)
                                        && PreferenceManager.getDefaultSharedPreferences(mContext)
                                                .getString(Settings.PREF_USERNAME + j,
                                                        Settings.DEFAULT_USERNAME)
                                                .length() != 0
                                        && PreferenceManager.getDefaultSharedPreferences(mContext)
                                                .getString(Settings.PREF_PORT + j, Settings.DEFAULT_PORT)
                                                .equals(Settings.DEFAULT_PORT))
                                    edit.putString(Settings.PREF_PORT + j, "5061");
                            }
                            edit.commit();
                            Receiver.engine(mContext).halt();
                            Receiver.engine(mContext).StartEngine();
                        }
                    }).setNeutralButton(R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                        }
                    }).setNegativeButton(R.string.dontask, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            Editor edit = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
                            edit.putBoolean(Settings.PREF_NOPORT, true);
                            edit.commit();
                        }
                    }).show();
    } else if (PreferenceManager.getDefaultSharedPreferences(this)
            .getString(Settings.PREF_PREF, Settings.DEFAULT_PREF).equals(Settings.VAL_PREF_PSTN)
            && !PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Settings.PREF_NODEFAULT,
                    Settings.DEFAULT_NODEFAULT))
        new AlertDialog.Builder(this).setMessage(R.string.dialog_default)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Editor edit = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
                        edit.putString(Settings.PREF_PREF, Settings.VAL_PREF_SIP);
                        edit.commit();
                    }
                }).setNeutralButton(R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                    }
                }).setNegativeButton(R.string.dontask, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Editor edit = PreferenceManager.getDefaultSharedPreferences(mContext).edit();
                        edit.putBoolean(Settings.PREF_NODEFAULT, true);
                        edit.commit();
                    }
                }).show();
}

From source file:com.activiti.android.ui.fragments.form.picker.IdmPickerFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (getArguments() != null) {
        onRetrieveParameters(getArguments());
    }/*from w w  w .  j a v  a 2s  .c o  m*/

    // Create View
    setRootView(inflater.inflate(R.layout.fr_idm_picker, container, false));

    // Init list
    init(getRootView(), emptyListMessageId);
    gv.setChoiceMode(GridView.CHOICE_MODE_SINGLE);
    setListShown(true);

    searchView = UIUtils.setActionBarCustomView(getActivity(), R.layout.person_picker_header, true);

    View searchBack = searchView.findViewById(R.id.search_back);
    searchBack.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            getActivity().getSupportFragmentManager().popBackStackImmediate();
        }
    });

    if (keywords != null && !keywords.isEmpty()) {
        search(keywords);
    } else {
        // Speech to Text
        hasTextToSpeech = FeatureUtils.hasSpeechToText(getActivity());
        speechToText = (ImageButton) searchView.findViewById(R.id.search_microphone);
        if (hasTextToSpeech) {
            speechToText.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    speechToText();
                }
            });
        } else {
            speechToText.setVisibility(View.GONE);
        }

        searchAction = (ImageButton) searchView.findViewById(R.id.search_start);
        searchAction.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (searchForm.getText().length() > 0) {
                    keywords = searchForm.getText().toString();
                    search(keywords);
                } else {
                    // TODO Snackbar
                }
            }
        });
        searchAction.setVisibility(View.GONE);

        // Init form search
        searchForm = (EditText) searchView.findViewById(R.id.search_query);
        searchForm.requestFocus();
        UIUtils.showKeyboard(getActivity(), searchForm);
        searchForm.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        searchForm.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

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

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    searchAction.setVisibility(View.GONE);
                    if (hasTextToSpeech) {
                        speechToText.setVisibility(View.VISIBLE);
                    }
                } else {
                    speechToText.setVisibility(View.GONE);
                    searchAction.setVisibility(View.VISIBLE);
                }
            }
        });

        searchForm.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event != null && (event.getAction() == KeyEvent.ACTION_DOWN)
                        && ((actionId == EditorInfo.IME_ACTION_SEARCH)
                                || (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
                                || (actionId == EditorInfo.IME_ACTION_DONE))) {
                    if (searchForm.getText().length() > 0) {
                        keywords = searchForm.getText().toString();
                        search(keywords);
                    } else {
                        // TODO Snackbar
                    }
                    return true;
                }
                return false;
            }
        });
    }

    if (getMode() == MODE_PICK) {
        Button cancel = UIUtils.initCancel(getRootView(), R.string.general_action_cancel);
        cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getDialog() != null) {
                    getDialog().dismiss();
                } else {
                    getFragmentManager().popBackStack();
                }
            }
        });
    } else {
        hide(R.id.validation_panel);
    }

    return getRootView();
}

From source file:uk.org.rivernile.edinburghbustracker.android.fragments.general.EnterStopCodeFragment.java

/**
 * {@inheritDoc}//  ww w  .j av a2s.  c  o m
 */
@Override
public boolean onKey(final View v, final int keyCode, final KeyEvent event) {
    // Grab the enter key.
    if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER
            && txt.getText().length() == 8) {
        imm.hideSoftInputFromWindow(txt.getWindowToken(), 0);
        task();
    }

    return false;
}

From source file:com.irccloud.android.activity.QuickReplyActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quick_reply);

    if (getIntent().hasExtra("cid") && getIntent().hasExtra("bid")) {
        onNewIntent(getIntent());/*from  ww w . j ava  2s.  c o  m*/
    } else {
        finish();
        return;
    }

    final ImageButton send = (ImageButton) findViewById(R.id.sendBtn);
    final EditText message = (EditText) findViewById(R.id.messageTxt);
    message.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            if (actionId == EditorInfo.IME_ACTION_SEND && message.getText() != null
                    && message.getText().length() > 0)
                send.performClick();
            return true;
        }
    });
    message.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER
                    && message.getText() != null && message.getText().length() > 0)
                send.performClick();
            return false;
        }
    });
    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (message.getText() != null && message.getText().length() > 0) {
                Intent i = new Intent(RemoteInputService.ACTION_REPLY);
                i.setComponent(new ComponentName(getPackageName(), RemoteInputService.class.getName()));
                i.putExtras(getIntent());
                i.putExtra("reply", message.getText().toString());
                startService(i);
                finish();
            }
        }
    });

    ListView listView = (ListView) findViewById(R.id.conversation);
    listView.setAdapter(adapter);
}

From source file:org.xwalk.core.xwview.shell.XWalkViewShellActivity.java

private void initializeUrlField() {
    mUrlTextView = (EditText) findViewById(R.id.url);
    mUrlTextView.setOnEditorActionListener(new OnEditorActionListener() {
        @Override// ww  w .  j av  a  2s. c  o  m
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if ((actionId != EditorInfo.IME_ACTION_GO)
                    && (event == null || event.getKeyCode() != KeyEvent.KEYCODE_ENTER
                            || event.getAction() != KeyEvent.ACTION_DOWN)) {
                return false;
            }

            if (mActiveView == null)
                return true;
            mActiveView.load(sanitizeUrl(mUrlTextView.getText().toString()), null);
            mUrlTextView.clearFocus();
            setKeyboardVisibilityForUrl(false);
            return true;
        }
    });
    mUrlTextView.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            setKeyboardVisibilityForUrl(hasFocus);
            mNextButton.setVisibility(hasFocus ? View.GONE : View.VISIBLE);
            mPrevButton.setVisibility(hasFocus ? View.GONE : View.VISIBLE);
            mStopButton.setVisibility(hasFocus ? View.GONE : View.VISIBLE);
            mReloadButton.setVisibility(hasFocus ? View.GONE : View.VISIBLE);
            if (!hasFocus) {
                if (mActiveView == null)
                    return;
                mUrlTextView.setText(mActiveView.getUrl());
            }
        }
    });
}

From source file:com.stoutner.privacybrowser.MainWebViewActivity.java

@Override
// Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.  The whole premise of Privacy Browser is built around an understanding of these dangers.
@SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_coordinatorlayout);

    // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
    Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
    setSupportActionBar(supportAppBar);/*from  w w w. j ava 2s  . c om*/
    final ActionBar appBar = getSupportActionBar();

    // This is needed to get rid of the Android Studio warning that appBar might be null.
    assert appBar != null;

    // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
    appBar.setCustomView(R.layout.url_bar);
    appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

    // Set the "go" button on the keyboard to load the URL in urlTextBox.
    urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
    urlTextBox.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button, load the URL.
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                // Load the URL into the mainWebView and consume the event.
                try {
                    loadUrlFromTextBox();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                // If the enter key was pressed, consume the event.
                return true;
            } else {
                // If any other key was pressed, do not consume the event.
                return false;
            }
        }
    });

    final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);

    // Implement swipe to refresh
    swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
    assert swipeToRefresh != null; //This assert removes the incorrect warning on the following line that swipeToRefresh might be null.
    swipeToRefresh.setColorSchemeResources(R.color.blue);
    swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mainWebView.reload();
        }
    });

    mainWebView = (WebView) findViewById(R.id.mainWebView);

    // Create the navigation drawer.
    drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    // The DrawerTitle identifies the drawer in accessibility mode.
    drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));

    // Listen for touches on the navigation menu.
    final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
    assert navigationView != null; // This assert removes the incorrect warning on the following line that navigationView might be null.
    navigationView.setNavigationItemSelectedListener(this);

    // drawerToggle creates the hamburger icon at the start of the AppBar.
    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation,
            R.string.close_navigation);

    mainWebView.setWebViewClient(new WebViewClient() {
        // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            mainWebView.loadUrl(url);
            return true;
        }

        // Update the URL in urlTextBox when the page starts to load.
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            urlTextBox.setText(url);
        }

        // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
        @Override
        public void onPageFinished(WebView view, String url) {
            formattedUrlString = url;

            // Only update urlTextBox if the user is not typing in it.
            if (!urlTextBox.hasFocus()) {
                urlTextBox.setText(formattedUrlString);
            }
        }
    });

    mainWebView.setWebChromeClient(new WebChromeClient() {
        // Update the progress bar when a page is loading.
        @Override
        public void onProgressChanged(WebView view, int progress) {
            // Make sure that appBar is not null.
            if (appBar != null) {
                ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
                progressBar.setProgress(progress);
                if (progress < 100) {
                    progressBar.setVisibility(View.VISIBLE);
                } else {
                    progressBar.setVisibility(View.GONE);

                    //Stop the SwipeToRefresh indicator if it is running
                    swipeToRefresh.setRefreshing(false);
                }
            }
        }

        // Set the favorite icon when it changes.
        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
            favoriteIcon = icon;

            // Place the favorite icon in the appBar if it is not null.
            if (appBar != null) {
                ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView()
                        .findViewById(R.id.favoriteIcon);
                imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
            }
        }

        // Enter full screen video
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            if (appBar != null) {
                appBar.hide();
            }

            // Show the fullScreenVideoFrameLayout.
            assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
            fullScreenVideoFrameLayout.addView(view);
            fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);

            // Hide the mainWebView.
            mainWebView.setVisibility(View.GONE);

            // Hide the ad if this is the free flavor.
            BannerAd.hideAd(adView);

            /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
             * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
             * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
             */

            // Set the one flag supported by API >= 14.
            view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

            // Set the two flags that are supported by API >= 16.
            if (Build.VERSION.SDK_INT >= 16) {
                view.setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
            }

            // Set all three flags that are supported by API >= 19.
            if (Build.VERSION.SDK_INT >= 19) {
                view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
            }
        }

        // Exit full screen video
        public void onHideCustomView() {
            if (appBar != null) {
                appBar.show();
            }

            // Show the mainWebView.
            mainWebView.setVisibility(View.VISIBLE);

            // Show the ad if this is the free flavor.
            BannerAd.showAd(adView);

            // Hide the fullScreenVideoFrameLayout.
            assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
            fullScreenVideoFrameLayout.removeAllViews();
            fullScreenVideoFrameLayout.setVisibility(View.GONE);
        }
    });

    // Allow the downloading of files.
    mainWebView.setDownloadListener(new DownloadListener() {
        // Launch the Android download manager when a link leads to a download.
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));

            // Add the URL as the description for the download.
            requestUri.setDescription(url);

            // Show the download notification after the download is completed.
            requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            // Initiate the download and display a Snackbar.
            downloadManager.enqueue(requestUri);
            Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT)
                    .show();
        }
    });

    // Allow pinch to zoom.
    mainWebView.getSettings().setBuiltInZoomControls(true);

    // Hide zoom controls.
    mainWebView.getSettings().setDisplayZoomControls(false);

    // Initialize the default preference values the first time the program is run.
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    // Get the shared preference values.
    SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Set JavaScript initial status.  The default value is false.
    javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
    mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);

    // Initialize cookieManager.
    cookieManager = CookieManager.getInstance();

    // Set cookies initial status.  The default value is false.
    firstPartyCookiesEnabled = savedPreferences.getBoolean("first_party_cookies_enabled", false);
    cookieManager.setAcceptCookie(firstPartyCookiesEnabled);

    // Set third-party cookies initial status if API >= 21.  The default value is false.
    if (Build.VERSION.SDK_INT >= 21) {
        thirdPartyCookiesEnabled = savedPreferences.getBoolean("third_party_cookies_enabled", false);
        cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
    }

    // Set DOM storage initial status.  The default value is false.
    domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
    mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);

    // Set the user agent initial status.
    String userAgentString = savedPreferences.getString("user_agent", "Default user agent");
    switch (userAgentString) {
    case "Default user agent":
        // Do nothing.
        break;

    case "Custom user agent":
        // Set the custom user agent on mainWebView,  The default is "PrivacyBrowser/1.0".
        mainWebView.getSettings()
                .setUserAgentString(savedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0"));
        break;

    default:
        // Set the selected user agent on mainWebView.  The default is "PrivacyBrowser/1.0".
        mainWebView.getSettings()
                .setUserAgentString(savedPreferences.getString("user_agent", "PrivacyBrowser/1.0"));
        break;
    }

    // Set the initial string for JavaScript disabled search.
    if (savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=")
            .equals("Custom URL")) {
        // Get the custom URL string.  The default is "".
        javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search_custom_url", "");
    } else {
        // Use the string from javascript_disabled_search.
        javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search",
                "https://duckduckgo.com/html/?q=");
    }

    // Set the initial string for JavaScript enabled search.
    if (savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=")
            .equals("Custom URL")) {
        // Get the custom URL string.  The default is "".
        javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search_custom_url", "");
    } else {
        // Use the string from javascript_enabled_search.
        javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search",
                "https://duckduckgo.com/?q=");
    }

    // Set homepage initial status.  The default value is "https://www.duckduckgo.com".
    homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");

    // Set swipe to refresh initial status.  The default is true.
    swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true);
    swipeToRefresh.setEnabled(swipeToRefreshEnabled);

    // Get the intent information that started the app.
    final Intent intent = getIntent();

    if (intent.getData() != null) {
        // Get the intent data and convert it to a string.
        final Uri intentUriData = intent.getData();
        formattedUrlString = intentUriData.toString();
    }

    // If formattedUrlString is null assign the homepage to it.
    if (formattedUrlString == null) {
        formattedUrlString = homepage;
    }

    // Load the initial website.
    mainWebView.loadUrl(formattedUrlString);

    // Initialize AdView for the free flavor and request an ad.  If this is not the free flavor BannerAd.requestAd() does nothing.
    adView = findViewById(R.id.adView);
    BannerAd.requestAd(adView);
}

From source file:org.mariotaku.twidere.fragment.AbsStatusesFragment.java

@Override
public boolean handleKeyboardShortcutSingle(@NonNull KeyboardShortcutsHandler handler, int keyCode,
        @NonNull KeyEvent event, int metaState) {
    String action = handler.getKeyAction(CONTEXT_TAG_NAVIGATION, keyCode, event, metaState);
    if (ACTION_NAVIGATION_REFRESH.equals(action)) {
        triggerRefresh();//from  www. ja va  2  s.c om
        return true;
    }
    final RecyclerView recyclerView = getRecyclerView();
    final LinearLayoutManager layoutManager = getLayoutManager();
    if (recyclerView == null || layoutManager == null)
        return false;
    final View focusedChild = RecyclerViewUtils.findRecyclerViewChild(recyclerView,
            layoutManager.getFocusedChild());
    int position = -1;
    if (focusedChild != null && focusedChild.getParent() == recyclerView) {
        position = recyclerView.getChildLayoutPosition(focusedChild);
    }
    if (position != -1) {
        final ParcelableStatus status = getAdapter().getStatus(position);
        if (status == null)
            return false;
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
            IntentUtils.openStatus(getActivity(), status, null);
            return true;
        }
        if (action == null) {
            action = handler.getKeyAction(CONTEXT_TAG_STATUS, keyCode, event, metaState);
        }
        if (action == null)
            return false;
        switch (action) {
        case ACTION_STATUS_REPLY: {
            final Intent intent = new Intent(INTENT_ACTION_REPLY);
            intent.putExtra(EXTRA_STATUS, status);
            startActivity(intent);
            return true;
        }
        case ACTION_STATUS_RETWEET: {
            RetweetQuoteDialogFragment.show(getFragmentManager(), status);
            return true;
        }
        case ACTION_STATUS_FAVORITE: {
            final AsyncTwitterWrapper twitter = mTwitterWrapper;
            if (status.is_favorite) {
                twitter.destroyFavoriteAsync(status.account_key, status.id);
            } else {
                final IStatusViewHolder holder = (IStatusViewHolder) recyclerView
                        .findViewHolderForLayoutPosition(position);
                holder.playLikeAnimation(new DefaultOnLikedListener(twitter, status));
            }
            return true;
        }
        }
    }
    return mNavigationHelper.handleKeyboardShortcutSingle(handler, keyCode, event, metaState);
}

From source file:org.mariotaku.twidere.fragment.AbsActivitiesFragment.java

@Override
public boolean handleKeyboardShortcutSingle(@NonNull KeyboardShortcutsHandler handler, int keyCode,
        @NonNull KeyEvent event, int metaState) {
    String action = handler.getKeyAction(CONTEXT_TAG_NAVIGATION, keyCode, event, metaState);
    if (ACTION_NAVIGATION_REFRESH.equals(action)) {
        triggerRefresh();//from w  w  w.j a va  2 s.  com
        return true;
    }
    final RecyclerView recyclerView = getRecyclerView();
    final LinearLayoutManager layoutManager = getLayoutManager();
    if (recyclerView == null || layoutManager == null)
        return false;
    final View focusedChild = RecyclerViewUtils.findRecyclerViewChild(recyclerView,
            layoutManager.getFocusedChild());
    int position = RecyclerView.NO_POSITION;
    if (focusedChild != null && focusedChild.getParent() == recyclerView) {
        position = recyclerView.getChildLayoutPosition(focusedChild);
    }
    if (position != RecyclerView.NO_POSITION) {
        final ParcelableActivity activity = getAdapter().getActivity(position);
        if (activity == null)
            return false;
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
            openActivity(activity);
            return true;
        }
        final ParcelableStatus status = ParcelableActivityUtils.getActivityStatus(activity);
        if (status == null)
            return false;
        if (action == null) {
            action = handler.getKeyAction(CONTEXT_TAG_STATUS, keyCode, event, metaState);
        }
        if (action == null)
            return false;
        switch (action) {
        case ACTION_STATUS_REPLY: {
            final Intent intent = new Intent(INTENT_ACTION_REPLY);
            intent.putExtra(EXTRA_STATUS, status);
            startActivity(intent);
            return true;
        }
        case ACTION_STATUS_RETWEET: {
            RetweetQuoteDialogFragment.show(getFragmentManager(), status);
            return true;
        }
        case ACTION_STATUS_FAVORITE: {
            final AsyncTwitterWrapper twitter = mTwitterWrapper;
            if (status.is_favorite) {
                twitter.destroyFavoriteAsync(status.account_key, status.id);
            } else {
                final IStatusViewHolder holder = (IStatusViewHolder) recyclerView
                        .findViewHolderForLayoutPosition(position);
                holder.playLikeAnimation(new DefaultOnLikedListener(twitter, status));
            }
            return true;
        }
        }
    }
    return mNavigationHelper.handleKeyboardShortcutSingle(handler, keyCode, event, metaState);
}