Example usage for android.view KeyEvent getAction

List of usage examples for android.view KeyEvent getAction

Introduction

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

Prototype

public final int getAction() 

Source Link

Document

Retrieve the action of this key event.

Usage

From source file:de.azapps.mirakel.main_activity.tasks_fragment.TasksFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    this.main = (MainActivity) getActivity();
    this.listId = this.main.getCurrentList().getId();
    this.view = inflater.inflate(R.layout.layout_tasks_fragment, container, false);
    this.adapter = null;
    this.created = true;
    this.listView = (ListView) this.view.findViewById(R.id.tasks_list);
    this.listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
    // Events//from  w ww  .  j av a 2 s .  c o m
    this.newTask = (EditText) this.view.findViewById(R.id.tasks_new);
    if (MirakelCommonPreferences.isTablet()) {
        this.newTask.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
    }
    this.newTask.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEND
                    || actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) {
                newTask(v.getText().toString());
                v.setText(null);
            }
            return false;
        }
    });
    this.newTask.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(final Editable s) {
            final ImageButton send = (ImageButton) TasksFragment.this.view.findViewById(R.id.btnEnter);
            if (s.length() > 0) {
                send.setVisibility(View.VISIBLE);
            } else {
                send.setVisibility(View.GONE);
            }
        }

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

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
            // Nothing
        }
    });
    update(true);
    final ImageButton btnEnter = (ImageButton) this.view.findViewById(R.id.btnEnter);
    btnEnter.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            newTask(TasksFragment.this.newTask.getText().toString());
            TasksFragment.this.newTask.setText(null);
        }
    });
    updateButtons();
    return this.view;
}

From source file:com.italankin.dictionary.ui.main.MainActivity.java

private void setupInputLayout() {
    mInputLayout.setOnClickListener(new View.OnClickListener() {
        @Override// w  ww.  j  a va  2 s .  c om
        public void onClick(View v) {
            mInput.requestFocus();
            mInputManager.showSoftInput(mInput, 0);
        }
    });
    ViewTreeObserver vto = mInputLayout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT >= 16) {
                ViewTreeObserver vto = mInputLayout.getViewTreeObserver();
                vto.removeOnGlobalLayoutListener(this);
            }
            updateInputLayoutPosition();
        }
    });

    mInput.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                lookupNext(mInput.getText().toString());
                return true;
            }
            return false;
        }
    });
}

From source file:org.mozilla.gecko.AwesomeBar.java

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

    Log.d(LOGTAG, "creating awesomebar");

    mResolver = Tabs.getInstance().getContentResolver();

    setContentView(R.layout.awesomebar);

    if (Build.VERSION.SDK_INT >= 11) {
        RelativeLayout actionBarLayout = (RelativeLayout) GeckoActionBar.getCustomView(this);
        mGoButton = (ImageButton) actionBarLayout.findViewById(R.id.awesomebar_button);
        mText = (AwesomeBarEditText) actionBarLayout.findViewById(R.id.awesomebar_text);
    } else {/*from  w  ww  .  java  2 s  . c  om*/
        mGoButton = (ImageButton) findViewById(R.id.awesomebar_button);
        mText = (AwesomeBarEditText) findViewById(R.id.awesomebar_text);
    }

    TabWidget tabWidget = (TabWidget) findViewById(android.R.id.tabs);
    tabWidget.setDividerDrawable(null);

    mAwesomeTabs = (AwesomeBarTabs) findViewById(R.id.awesomebar_tabs);
    mAwesomeTabs.setOnUrlOpenListener(new AwesomeBarTabs.OnUrlOpenListener() {
        public void onUrlOpen(String url) {
            openUrlAndFinish(url);
        }

        public void onSearch(String engine) {
            openSearchAndFinish(mText.getText().toString(), engine);
        }
    });

    mGoButton.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            openUserEnteredAndFinish(mText.getText().toString());
        }
    });

    Resources resources = getResources();

    int padding[] = { mText.getPaddingLeft(), mText.getPaddingTop(), mText.getPaddingRight(),
            mText.getPaddingBottom() };

    GeckoStateListDrawable states = new GeckoStateListDrawable();
    states.initializeFilter(GeckoApp.mBrowserToolbar.getHighlightColor());
    states.addState(new int[] { android.R.attr.state_focused },
            resources.getDrawable(R.drawable.address_bar_url_pressed));
    states.addState(new int[] { android.R.attr.state_pressed },
            resources.getDrawable(R.drawable.address_bar_url_pressed));
    states.addState(new int[] {}, resources.getDrawable(R.drawable.address_bar_url_default));
    mText.setBackgroundDrawable(states);

    mText.setPadding(padding[0], padding[1], padding[2], padding[3]);

    Intent intent = getIntent();
    String currentUrl = intent.getStringExtra(CURRENT_URL_KEY);
    mType = intent.getStringExtra(TYPE_KEY);
    if (currentUrl != null) {
        mText.setText(currentUrl);
        mText.selectAll();
    }

    mText.setOnKeyPreImeListener(new AwesomeBarEditText.OnKeyPreImeListener() {
        public boolean onKeyPreIme(View v, int keyCode, KeyEvent event) {
            // We only want to process one event per tap
            if (event.getAction() != KeyEvent.ACTION_DOWN)
                return false;

            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                openUserEnteredAndFinish(mText.getText().toString());
                return true;
            }

            // If input method is in fullscreen mode, we want to dismiss
            // it instead of closing awesomebar straight away.
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (keyCode == KeyEvent.KEYCODE_BACK && !imm.isFullscreenMode()) {
                // Let mAwesomeTabs try to handle the back press, since we may be in a
                // bookmarks sub-folder.
                if (mAwesomeTabs.onBackPressed())
                    return true;

                // If mAwesomeTabs.onBackPressed() returned false, we didn't move up
                // a folder level, so just exit the activity.
                cancelAndFinish();
                return true;
            }

            return false;
        }
    });

    mText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            // do nothing
        }

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

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String text = s.toString();

            mAwesomeTabs.filter(text);
            updateGoButton(text);
        }
    });

    mText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                if (event.getAction() != KeyEvent.ACTION_DOWN)
                    return true;

                openUserEnteredAndFinish(mText.getText().toString());
                return true;
            } else {
                return false;
            }
        }
    });

    mText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    });

    registerForContextMenu(mAwesomeTabs.findViewById(R.id.all_pages_list));
    registerForContextMenu(mAwesomeTabs.findViewById(R.id.bookmarks_list));
    registerForContextMenu(mAwesomeTabs.findViewById(R.id.history_list));

    GeckoAppShell.registerGeckoEventListener("SearchEngines:Data", this);
    GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("SearchEngines:Get", null));
}

From source file:com.nxt.yn.app.ui.MainActivity.java

public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            //                Snackbar snackbar=Snackbar.make(getCurrentFocus(), R.string.exit_notice, Snackbar.LENGTH_SHORT);
            //                TextView textView= (TextView) snackbar.getView().findViewById(R.id.snackbar_text);
            //                textView.setGravity(Gravity.CENTER);
            //                snackbar.getView().setBackgroundColor(getResources().getColor(ZPreferenceUtils.getPrefInt(com.nxt.ott.util.Constant.SKIN_COLOR, getResources().getColor(R.color.title_color))));
            //                snackbar.show();
            Toast.makeText(getApplicationContext(), getString(R.string.exit_notice), Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {/*from  w  w  w.  jav a 2 s.  c o m*/
            MyApplication.getInstance().exit();
            finish();
        }
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

From source file:ayushi.view.fragment.ProductDetailsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.frag_product_detail, container, false);

    mToolbar = (Toolbar) rootView.findViewById(R.id.htab_toolbar);
    if (mToolbar != null) {
        ((ECartHomeActivity) getActivity()).setSupportActionBar(mToolbar);
    }/*from w ww.j a  va 2  s.  c  o  m*/

    if (mToolbar != null) {
        ((ECartHomeActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mToolbar.setNavigationIcon(R.drawable.ic_drawer);

    }

    mToolbar.setTitleTextColor(Color.WHITE);

    mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((ECartHomeActivity) getActivity()).getmDrawerLayout().openDrawer(GravityCompat.START);
        }
    });

    ((ECartHomeActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    similarProductsPager = (ClickableViewPager) rootView.findViewById(R.id.similar_products_pager);

    topSellingPager = (ClickableViewPager) rootView.findViewById(R.id.top_selleing_pager);

    itemSellPrice = ((TextView) rootView.findViewById(R.id.category_discount));

    quanitity = ((TextView) rootView.findViewById(R.id.iteam_amount));

    itemName = ((TextView) rootView.findViewById(R.id.product_name));

    itemdescription = ((TextView) rootView.findViewById(R.id.product_description));

    itemImage = (ImageView) rootView.findViewById(R.id.product_image);

    fillProductData();

    rootView.findViewById(R.id.add_item).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (isFromCart) {

                //Update Quantity on shopping List
                GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(productListNumber)
                        .setQuantity(String.valueOf(

                                Integer.valueOf(GlobaDataHolder.getGlobaDataHolder().getShoppingList()
                                        .get(productListNumber).getQuantity()) + 1));

                //Update Ui
                quanitity.setText(GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(productListNumber)
                        .getQuantity());

                Utils.vibrate(getActivity());

                //Update checkout amount on screen
                ((ECartHomeActivity) getActivity()).updateCheckOutAmount(
                        BigDecimal.valueOf(Long.valueOf(GlobaDataHolder.getGlobaDataHolder().getShoppingList()
                                .get(productListNumber).getSellMRP())),
                        true);

            } else {

                // current object
                Product tempObj = GlobaDataHolder.getGlobaDataHolder().getProductMap().get(subcategoryKey)
                        .get(productListNumber);

                // if current object is lready in shopping list
                if (GlobaDataHolder.getGlobaDataHolder().getShoppingList().contains(tempObj)) {

                    // get position of current item in shopping list
                    int indexOfTempInShopingList = GlobaDataHolder.getGlobaDataHolder().getShoppingList()
                            .indexOf(tempObj);

                    // increase quantity of current item in shopping
                    // list
                    if (Integer.parseInt(tempObj.getQuantity()) == 0) {

                        ((ECartHomeActivity) getContext()).updateItemCount(true);

                    }

                    // update quanity in shopping list
                    GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(indexOfTempInShopingList)
                            .setQuantity(String.valueOf(Integer.valueOf(tempObj.getQuantity()) + 1));

                    // update checkout amount
                    ((ECartHomeActivity) getContext())
                            .updateCheckOutAmount(
                                    BigDecimal.valueOf(
                                            Long.valueOf(GlobaDataHolder.getGlobaDataHolder().getProductMap()
                                                    .get(subcategoryKey).get(productListNumber).getSellMRP())),
                                    true);

                    // update current item quanitity
                    quanitity.setText(tempObj.getQuantity());

                } else {

                    ((ECartHomeActivity) getContext()).updateItemCount(true);

                    tempObj.setQuantity(String.valueOf(1));

                    quanitity.setText(tempObj.getQuantity());

                    GlobaDataHolder.getGlobaDataHolder().getShoppingList().add(tempObj);

                    ((ECartHomeActivity) getContext())
                            .updateCheckOutAmount(
                                    BigDecimal.valueOf(
                                            Long.valueOf(GlobaDataHolder.getGlobaDataHolder().getProductMap()
                                                    .get(subcategoryKey).get(productListNumber).getSellMRP())),
                                    true);

                }

                Utils.vibrate(getContext());

            }
        }

    });

    rootView.findViewById(R.id.remove_item).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (isFromCart)

            {

                if (Integer.valueOf(GlobaDataHolder.getGlobaDataHolder().getShoppingList()
                        .get(productListNumber).getQuantity()) > 2) {

                    GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(productListNumber)
                            .setQuantity(String.valueOf(

                                    Integer.valueOf(GlobaDataHolder.getGlobaDataHolder().getShoppingList()
                                            .get(productListNumber).getQuantity()) - 1));

                    quanitity.setText(GlobaDataHolder.getGlobaDataHolder().getShoppingList()
                            .get(productListNumber).getQuantity());

                    ((ECartHomeActivity) getActivity()).updateCheckOutAmount(
                            BigDecimal.valueOf(Long.valueOf(GlobaDataHolder.getGlobaDataHolder()
                                    .getShoppingList().get(productListNumber).getSellMRP())),
                            false);

                    Utils.vibrate(getActivity());
                }

                else if (Integer.valueOf(GlobaDataHolder.getGlobaDataHolder().getShoppingList()
                        .get(productListNumber).getQuantity()) == 1) {
                    ((ECartHomeActivity) getActivity()).updateItemCount(false);

                    ((ECartHomeActivity) getActivity()).updateCheckOutAmount(
                            BigDecimal.valueOf(Long.valueOf(GlobaDataHolder.getGlobaDataHolder()
                                    .getShoppingList().get(productListNumber).getSellMRP())),
                            false);

                    GlobaDataHolder.getGlobaDataHolder().getShoppingList().remove(productListNumber);

                    if (Integer.valueOf(((ECartHomeActivity) getActivity()).getItemCount()) == 0) {

                        MyCartFragment.updateMyCartFragment(false);

                    }

                    Utils.vibrate(getActivity());

                }

            }

            else {

                Product tempObj = GlobaDataHolder.getGlobaDataHolder().getProductMap().get(subcategoryKey)
                        .get(productListNumber);

                if (GlobaDataHolder.getGlobaDataHolder().getShoppingList().contains(tempObj)) {

                    int indexOfTempInShopingList = GlobaDataHolder.getGlobaDataHolder().getShoppingList()
                            .indexOf(tempObj);

                    if (Integer.valueOf(tempObj.getQuantity()) != 0) {

                        GlobaDataHolder.getGlobaDataHolder().getShoppingList().get(indexOfTempInShopingList)
                                .setQuantity(String.valueOf(Integer.valueOf(tempObj.getQuantity()) - 1));

                        ((ECartHomeActivity) getContext()).updateCheckOutAmount(
                                BigDecimal.valueOf(
                                        Long.valueOf(GlobaDataHolder.getGlobaDataHolder().getProductMap()
                                                .get(subcategoryKey).get(productListNumber).getSellMRP())),
                                false);

                        quanitity.setText(GlobaDataHolder.getGlobaDataHolder().getShoppingList()
                                .get(indexOfTempInShopingList).getQuantity());

                        Utils.vibrate(getContext());

                        if (Integer.valueOf(GlobaDataHolder.getGlobaDataHolder().getShoppingList()
                                .get(indexOfTempInShopingList).getQuantity()) == 0) {

                            GlobaDataHolder.getGlobaDataHolder().getShoppingList()
                                    .remove(indexOfTempInShopingList);

                            ((ECartHomeActivity) getContext()).updateItemCount(false);

                        }

                    }

                } else {

                }

            }

        }

    });

    rootView.setFocusableInTouchMode(true);
    rootView.requestFocus();
    rootView.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {

                if (isFromCart) {

                    Utils.switchContent(R.id.frag_container, Utils.SHOPPING_LIST_TAG,
                            ((ECartHomeActivity) (getActivity())), AnimationType.SLIDE_UP);
                } else {

                    Utils.switchContent(R.id.frag_container, Utils.PRODUCT_OVERVIEW_FRAGMENT_TAG,
                            ((ECartHomeActivity) (getActivity())), AnimationType.SLIDE_RIGHT);
                }

            }
            return true;
        }
    });

    if (isFromCart) {

        similarProductsPager.setVisibility(View.GONE);

        topSellingPager.setVisibility(View.GONE);

    } else {
        showRecomondation();
    }

    return rootView;
}

From source file:mgks.os.webview.MainActivity.java

@Override
public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
            if (asw_view.canGoBack()) {
                asw_view.goBack();//from www .  j ava2  s . c  o m
            } else {
                finish();
            }
            return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

From source file:com.sentaroh.android.BluetoothWidget.Log.LogFileListDialogFragment.java

@Override
public void onStart() {
    CommonDialog.setDlgBoxSizeLimit(mDialog, true);
    super.onStart();
    if (DEBUG_ENABLE)
        Log.v(APPLICATION_TAG, "onStart");
    if (mTerminateRequired)
        mDialog.cancel();/*  w  ww  .j  a v a  2 s.  c  o m*/
    else {
        mDialog.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                // disable search button action
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mLogFileManagementAdapter.isShowCheckBox()) {
                        for (int i = 0; i < mLogFileManagementAdapter.getCount(); i++) {
                            mLogFileManagementAdapter.getItem(i).isChecked = false;
                        }
                        mLogFileManagementAdapter.setShowCheckBox(false);
                        mLogFileManagementAdapter.notifyDataSetChanged();
                        setContextButtonNormalMode(mLogFileManagementAdapter);
                        return true;
                    }
                }
                return false;
            }
        });
    }
}

From source file:com.piusvelte.webcaster.MainActivity.java

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    int action = event.getAction();
    int keyCode = event.getKeyCode();
    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        if (action == KeyEvent.ACTION_DOWN) {
            double currentVolume;

            if (mediaProtocolMessageStream != null) {
                currentVolume = mediaProtocolMessageStream.getVolume();

                if (currentVolume < 1.0) {
                    onSetVolume(currentVolume + VOLUME_INCREMENT);
                }//from  ww  w . ja v a2s  .  c  o m
            } else {
                Log.e(TAG, "dispatchKeyEvent - volume up - mMPMS==null");
            }
        }

        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        if (action == KeyEvent.ACTION_DOWN) {
            double currentVolume;

            if (mediaProtocolMessageStream != null) {
                currentVolume = mediaProtocolMessageStream.getVolume();

                if (currentVolume > 0.0) {
                    onSetVolume(currentVolume - VOLUME_INCREMENT);
                }
            } else {
                Log.e(TAG, "dispatchKeyEvent - volume down - mMPMS==null");
            }
        }
        return true;
    default:
        return super.dispatchKeyEvent(event);
    }
}

From source file:org.telegram.ui.ActionBar.ActionBarMenuItem.java

public ActionBarMenuItem setIsSearchField(boolean value) {
    if (parentMenu == null) {
        return this;
    }//from   w  w  w  .ja  v  a  2s  .c  o  m
    if (value && searchContainer == null) {
        searchContainer = new FrameLayout(getContext());
        parentMenu.addView(searchContainer, 0);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) searchContainer.getLayoutParams();
        layoutParams.weight = 1;
        layoutParams.width = 0;
        layoutParams.height = LayoutHelper.MATCH_PARENT;
        layoutParams.leftMargin = AndroidUtilities.dp(6);
        searchContainer.setLayoutParams(layoutParams);
        searchContainer.setVisibility(GONE);

        searchField = new EditText(getContext());
        searchField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        searchField.setHintTextColor(0x88ffffff);
        searchField.setTextColor(0xffffffff);
        searchField.setSingleLine(true);
        searchField.setBackgroundResource(0);
        searchField.setPadding(0, 0, 0, 0);
        int inputType = searchField.getInputType() | EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
        searchField.setInputType(inputType);
        searchField.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public void onDestroyActionMode(ActionMode mode) {

            }

            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                return false;
            }
        });
        searchField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (/*actionId == EditorInfo.IME_ACTION_SEARCH || */event != null
                        && (event.getAction() == KeyEvent.ACTION_UP
                                && event.getKeyCode() == KeyEvent.KEYCODE_SEARCH
                                || event.getAction() == KeyEvent.ACTION_DOWN
                                        && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    AndroidUtilities.hideKeyboard(searchField);
                    if (listener != null) {
                        listener.onSearchPressed(searchField);
                    }
                }
                return false;
            }
        });
        searchField.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (listener != null) {
                    listener.onTextChanged(searchField);
                }
                if (clearButton != null) {
                    clearButton.setAlpha(s == null || s.length() == 0 ? 0.6f : 1.0f);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        try {
            Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
            mCursorDrawableRes.setAccessible(true);
            mCursorDrawableRes.set(searchField, R.drawable.search_carret);
        } catch (Exception e) {
            //nothing to do
        }
        searchField.setImeOptions(EditorInfo.IME_FLAG_NO_FULLSCREEN | EditorInfo.IME_ACTION_SEARCH);
        searchField.setTextIsSelectable(false);
        searchContainer.addView(searchField);
        FrameLayout.LayoutParams layoutParams2 = (FrameLayout.LayoutParams) searchField.getLayoutParams();
        layoutParams2.width = LayoutHelper.MATCH_PARENT;
        layoutParams2.gravity = Gravity.CENTER_VERTICAL;
        layoutParams2.height = AndroidUtilities.dp(36);
        layoutParams2.rightMargin = AndroidUtilities.dp(48);
        searchField.setLayoutParams(layoutParams2);

        clearButton = new ImageView(getContext());
        clearButton.setImageResource(R.drawable.ic_close_white);
        clearButton.setScaleType(ImageView.ScaleType.CENTER);
        clearButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                searchField.setText("");
                searchField.requestFocus();
                AndroidUtilities.showKeyboard(searchField);
            }
        });
        searchContainer.addView(clearButton);
        layoutParams2 = (FrameLayout.LayoutParams) clearButton.getLayoutParams();
        layoutParams2.width = AndroidUtilities.dp(48);
        layoutParams2.gravity = Gravity.CENTER_VERTICAL | Gravity.RIGHT;
        layoutParams2.height = LayoutHelper.MATCH_PARENT;
        clearButton.setLayoutParams(layoutParams2);
    }
    isSearchField = value;
    return this;
}

From source file:rdx.andro.forexcapplugins.childBrowser.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 * //  www  .j ava  2s . c  o  m
 * @param url
 *            The url to load.
 * @param jsonObject
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
    }

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         * 
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        public void run() {
            // Let's create the main dialog
            dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            ImageButton back = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            try {
                back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            ImageButton forward = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            try {
                forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except
            // input... Makes
            // the text
            // NON-EDITABLE
            edittext.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
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close button
            ImageButton close = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            try {
                close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            webview = new WebView(cordova.getActivity());
            webview.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
            webview.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new ChildBrowserClient(edittext);
            webview.setWebViewClient(client);
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            // settings.setPluginState(true);
            settings.setDomStorageEnabled(true);
            webview.loadUrl(url);
            webview.setId(6);
            webview.getSettings().setLoadWithOverviewMode(true);
            webview.getSettings().setUseWideViewPort(true);
            webview.requestFocus();
            webview.requestFocusFromTouch();

            // Add the back and forward buttons to our action button
            // container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            toolbar.addView(actionButtonContainer);
            toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(webview);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.FILL_PARENT;
            lp.height = WindowManager.LayoutParams.FILL_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            InputStream input = cordova.getActivity().getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}