Example usage for android.view KeyEvent ACTION_DOWN

List of usage examples for android.view KeyEvent ACTION_DOWN

Introduction

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

Prototype

int ACTION_DOWN

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

Click Source Link

Document

#getAction value: the key has been pressed down.

Usage

From source file:it.chefacile.app.MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mContext = this;
    chefacileDb = new DatabaseHelper(this);
    // FilterButton = (ImageButton) findViewById(R.id.buttonfilter);
    TutorialButton = (ImageButton) findViewById(R.id.button);
    //  AddButton = (ImageButton) findViewById(R.id.button2);
    responseView = (TextView) findViewById(R.id.responseView);
    editText = (EditText) findViewById(R.id.ingredientText);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    //Show = (ImageButton) findViewById(R.id.buttonShow);
    //Show2 = (ImageButton) findViewById(R.id.buttonShow2);
    materialAnimatedSwitch = (MaterialAnimatedSwitch) findViewById(R.id.pin);
    //buttoncuisine = (ImageButton) findViewById(R.id.btn_cuisine);
    //buttondiet = (ImageButton) findViewById(R.id.btn_diet);
    //buttonintol = (ImageButton) findViewById(R.id.btn_intoll);
    //Mostra = (Button) findViewById(R.id.btn_mostra);

    final Animation animation = new AlphaAnimation(1, 0); // Change alpha from fully visible to invisible
    animation.setDuration(1000); // duration - half a second
    animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
    animation.setRepeatCount(5); // Repeat animation infinitely
    animation.setRepeatMode(Animation.REVERSE);

    ImageView icon = new ImageView(this); // Create an icon
    icon.setImageDrawable(getResources().getDrawable(R.drawable.logo));

    final com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton actionButton = new com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton.Builder(
            this).setPosition(
                    com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton.POSITION_RIGHT_CENTER)
                    .setContentView(icon).build();

    SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this);
    // repeat many times:
    ImageView dietIcon = new ImageView(this);
    dietIcon.setImageDrawable(getResources().getDrawable(R.drawable.diet));
    SubActionButton button1 = itemBuilder.setContentView(dietIcon).build();
    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showSingleChoiceDialogDiet(v);
        }/*from w  ww .  ja v  a2  s.  c o  m*/
    });

    ImageView intolIcon = new ImageView(this);
    intolIcon.setImageDrawable(getResources().getDrawable(R.drawable.intoll));
    SubActionButton button2 = itemBuilder.setContentView(intolIcon).build();
    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showMultiChoiceDialogIntol(v);
        }
    });

    ImageView cuisineIcon = new ImageView(this);
    cuisineIcon.setImageDrawable(getResources().getDrawable(R.drawable.cook12));
    SubActionButton button3 = itemBuilder.setContentView(cuisineIcon).build();
    button3.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showMultiChoiceDialogCuisine(v);
        }
    });

    ImageView favouriteIcon = new ImageView(this);
    favouriteIcon.setImageDrawable(getResources().getDrawable(R.drawable.favorite));
    SubActionButton button4 = itemBuilder.setContentView(favouriteIcon).build();
    button4.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showSimpleListDialogFav(v);
        }
    });

    ImageView wandIcon = new ImageView(this);
    wandIcon.setImageDrawable(getResources().getDrawable(R.drawable.wand));
    SubActionButton button5 = itemBuilder.setContentView(wandIcon).build();
    button5.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            sugg = getSuggestion();
            suggOccurrences = getCount();
            showSimpleListDialogSuggestions(v);
        }
    });

    final FloatingActionButton actionABC = (FloatingActionButton) findViewById(R.id.action_abc);

    actionABC.bringToFront();
    actionABC.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (ingredients.length() < 2) {
                Snackbar.make(responseView, "Insert at least one ingredient", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            } else {
                new RetrieveFeedTask().execute();
            }
        }

        // Snackbar.make(view, "Non disponibile, mangia l'aria", Snackbar.LENGTH_LONG)
        //         .setAction("Action", null).show();

    });

    FloatingActionMenu actionMenu = new FloatingActionMenu.Builder(this).setStartAngle(90).setEndAngle(270)
            .addSubActionView(button1).addSubActionView(button2).addSubActionView(button3)
            .addSubActionView(button4).addSubActionView(button5).attachTo(actionButton).build();

    startDatabase(chefacileDb);

    for (int j = 0; j < cuisineItems.length; j++) {
        cuisineItems[j] = cuisineItems[j].substring(0, 1).toUpperCase() + cuisineItems[j].substring(1);
    }
    Arrays.sort(cuisineItems);

    for (int i = 0; i < 24; i++) {
        cuisineBool[i] = false;
    }

    Arrays.sort(intolItems);

    for (int i = 0; i < 11; i++) {
        intolBool[i] = false;
    }

    mListView = (MaterialListView) findViewById(R.id.material_listview);

    adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);

    TutorialButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, IntroScreenActivity.class));
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

        }
    });

    iv = (ImageView) findViewById(R.id.imageView);
    iv.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            clicks++;
            Log.d("CLICKS", String.valueOf(clicks));
            if (clicks == 15) {
                Log.d("IMAGE SHOWN", "mai vero");
                setBackground(iv);
            }
        }
    });

    materialAnimatedSwitch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(boolean isChecked) {
            if (isChecked == true) {
                ranking = 2;
                Toast.makeText(getApplicationContext(), "Minimize missing ingredients", Toast.LENGTH_SHORT)
                        .show();
            } else {
                ranking = 1;
                Toast.makeText(getApplicationContext(), "Maximize used ingredients", Toast.LENGTH_SHORT).show();
            }
            Log.d("Ranking", String.valueOf(ranking));
        }
    });

    final CharSequence[] items = { "Maximize used ingredients", "Minimize missing ingredients" };

    editText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_ENTER:
                    if (!(editText.getText().toString().trim().equals(""))) {

                        String input;
                        String s1 = editText.getText().toString().substring(0, 1).toUpperCase();
                        String s2 = editText.getText().toString().substring(1);
                        input = s1 + s2;

                        Log.d("INPUT: ", input);
                        searchedIngredients.add(input);
                        Log.d("SEARCHED INGR LIST", searchedIngredients.toString());

                        if (!chefacileDb.findIngredientPREF(input)) {
                            if (chefacileDb.findIngredient(input)) {
                                chefacileDb.updateCount(input);
                                mapIngredients = chefacileDb.getDataInMapIngredient();
                                Map<String, Integer> map2;
                                map2 = sortByValue(mapIngredients);
                                Log.d("MAPPACOUNT: ", map2.toString());

                            } else {
                                if (chefacileDb.occursExceeded()) {
                                    //chefacileDb.deleteMinimum(input);
                                    // chefacileDb.insertDataIngredient(input);
                                    mapIngredients = chefacileDb.getDataInMapIngredient();
                                    Map<String, Integer> map3;
                                    map3 = sortByValue(mapIngredients);
                                    Log.d("MAPPAINGREDIENTE: ", map3.toString());

                                } else {
                                    chefacileDb.insertDataIngredient(input);
                                    mapIngredients = chefacileDb.getDataInMapIngredient();
                                    Map<String, Integer> map3;
                                    map3 = sortByValue(mapIngredients);
                                    Log.d("MAPPAINGREDIENTE: ", map3.toString());
                                }
                            }
                        }
                    }

                    if (editText.getText().toString().trim().equals("")) {
                        ingredients += editText.getText().toString().trim() + "";
                        editText.getText().clear();

                    } else {
                        ingredients += editText.getText().toString().replaceAll(" ", "+").trim().toLowerCase()
                                + ",";
                        singleIngredient = editText.getText().toString().trim().toLowerCase();
                        currentIngredient = singleIngredient;
                        new RetrieveIngredientTask().execute();

                        //adapter.add(singleIngredient.substring(0,1).toUpperCase() + singleIngredient.substring(1));
                    }

                    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

                    in.hideSoftInputFromWindow(editText.getApplicationWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);

                    actionABC.startAnimation(animation);

                    return true;
                default:
                    break;
                }
            }
            return false;
        }
    });

    responseView = (TextView) findViewById(R.id.responseView);
    editText = (EditText) findViewById(R.id.ingredientText);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

}

From source file:com.google.android.apps.flexbox.FlexItemEditFragment.java

private void setNextFocusesOnEnterDown(final TextView... textViews) {
    // This can be done by setting android:nextFocus* as in 
    // https://developer.android.com/training/keyboard-input/navigation.html
    // But it requires API level 11 as a minimum sdk version. To support the lower level devices,
    // doing it programatically.
    for (int i = 0; i < textViews.length; i++) {
        final int index = i;
        textViews[index].setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override//from  w  w  w.  ja  v a  2s  . co m
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_DONE
                        || (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN
                                && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    if (index + 1 < textViews.length) {
                        textViews[index + 1].requestFocus();
                    } else if (index == textViews.length - 1) {
                        InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
                                .getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    }
                }
                return true;
            }
        });

        // Suppress the key focus change by KeyEvent.ACTION_UP of the enter key
        textViews[index].setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                return keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP;
            }
        });
    }

}

From source file:org.mklab.mikity.android.editor.AbstractObjectEditor.java

/**
 * {@inheritDoc}//from www  .  j  a va2  s  . c o m
 */
public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
        final InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
        saveParameters();
        return true;
    }

    return false;
}

From source file:nl.mpcjanssen.simpletask.AddTask.java

@Override
public void onCreate(Bundle savedInstanceState) {
    Log.v(TAG, "onCreate()");

    m_app = (TodoApplication) getApplication();
    m_app.setActionBarStyle(getWindow());
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    super.onCreate(savedInstanceState);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Constants.BROADCAST_UPDATE_UI);
    intentFilter.addAction(Constants.BROADCAST_SYNC_START);
    intentFilter.addAction(Constants.BROADCAST_SYNC_DONE);

    localBroadcastManager = m_app.getLocalBroadCastManager();

    m_broadcastReceiver = new BroadcastReceiver() {
        @Override/*from  w  w  w  .  ja  va2s  . c  o  m*/
        public void onReceive(Context context, @NotNull Intent intent) {
            if (intent.getAction().equals(Constants.BROADCAST_SYNC_START)) {
                setProgressBarIndeterminateVisibility(true);
            } else if (intent.getAction().equals(Constants.BROADCAST_SYNC_DONE)) {
                setProgressBarIndeterminateVisibility(false);
            }
        }
    };
    localBroadcastManager.registerReceiver(m_broadcastReceiver, intentFilter);

    ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
    final Intent intent = getIntent();
    ActiveFilter mFilter = new ActiveFilter();
    mFilter.initFromIntent(intent);
    final String action = intent.getAction();
    // create shortcut and exit
    if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
        Log.d(TAG, "Setting up shortcut icon");
        setupShortcut();
        finish();
        return;
    } else if (Intent.ACTION_SEND.equals(action)) {
        Log.d(TAG, "Share");
        if (intent.hasExtra(Intent.EXTRA_TEXT)) {
            share_text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT).toString();
        } else {
            share_text = "";
        }
        if (!m_app.hasShareTaskShowsEdit()) {
            if (!share_text.equals("")) {
                addBackgroundTask(share_text);
            }
            finish();
            return;
        }
    } else if ("com.google.android.gm.action.AUTO_SEND".equals(action)) {
        // Called as note to self from google search/now
        noteToSelf(intent);
        finish();
        return;
    } else if (Constants.INTENT_BACKGROUND_TASK.equals(action)) {
        Log.v(TAG, "Adding background task");
        if (intent.hasExtra(Constants.EXTRA_BACKGROUND_TASK)) {
            addBackgroundTask(intent.getStringExtra(Constants.EXTRA_BACKGROUND_TASK));
        } else {
            Log.w(TAG, "Task was not in extras");
        }
        finish();
        return;
    }

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);

    setContentView(R.layout.add_task);

    // text
    textInputField = (EditText) findViewById(R.id.taskText);
    m_app.setEditTextHint(textInputField, R.string.tasktexthint);

    if (share_text != null) {
        textInputField.setText(share_text);
    }

    Task iniTask = null;
    setTitle(R.string.addtask);

    m_backup = m_app.getTaskCache(this).getTasksToUpdate();
    if (m_backup != null && m_backup.size() > 0) {
        ArrayList<String> prefill = new ArrayList<String>();
        for (Task t : m_backup) {
            prefill.add(t.inFileFormat());
        }
        String sPrefill = Util.join(prefill, "\n");
        textInputField.setText(sPrefill);
        setTitle(R.string.updatetask);
    } else {
        if (textInputField.getText().length() == 0) {
            iniTask = new Task(1, "");
            iniTask.initWithFilter(mFilter);
        }

        if (iniTask != null && iniTask.getTags().size() == 1) {
            List<String> ps = iniTask.getTags();
            String project = ps.get(0);
            if (!project.equals("-")) {
                textInputField.append(" +" + project);
            }
        }

        if (iniTask != null && iniTask.getLists().size() == 1) {
            List<String> cs = iniTask.getLists();
            String context = cs.get(0);
            if (!context.equals("-")) {
                textInputField.append(" @" + context);
            }
        }
    }
    // Listen to enter events, use IME_ACTION_NEXT for soft keyboards
    // like Swype where ENTER keyCode is not generated.

    int inputFlags = InputType.TYPE_CLASS_TEXT;

    if (m_app.hasCapitalizeTasks()) {
        inputFlags |= InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;
    }
    textInputField.setRawInputType(inputFlags);
    textInputField.setImeOptions(EditorInfo.IME_ACTION_NEXT);
    textInputField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, @Nullable KeyEvent keyEvent) {

            boolean hardwareEnterUp = keyEvent != null && keyEvent.getAction() == KeyEvent.ACTION_UP
                    && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER;
            boolean hardwareEnterDown = keyEvent != null && keyEvent.getAction() == KeyEvent.ACTION_DOWN
                    && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER;
            boolean imeActionNext = (actionId == EditorInfo.IME_ACTION_NEXT);

            if (imeActionNext || hardwareEnterUp) {
                // Move cursor to end of line
                int position = textInputField.getSelectionStart();
                String remainingText = textInputField.getText().toString().substring(position);
                int endOfLineDistance = remainingText.indexOf('\n');
                int endOfLine;
                if (endOfLineDistance == -1) {
                    endOfLine = textInputField.length();
                } else {
                    endOfLine = position + endOfLineDistance;
                }
                textInputField.setSelection(endOfLine);
                replaceTextAtSelection("\n", false);

                if (hasCloneTags()) {
                    String precedingText = textInputField.getText().toString().substring(0, endOfLine);
                    int lineStart = precedingText.lastIndexOf('\n');
                    String line;
                    if (lineStart != -1) {
                        line = precedingText.substring(lineStart, endOfLine);
                    } else {
                        line = precedingText;
                    }
                    Task t = new Task(0, line);
                    LinkedHashSet<String> tags = new LinkedHashSet<String>();
                    for (String ctx : t.getLists()) {
                        tags.add("@" + ctx);
                    }
                    for (String prj : t.getTags()) {
                        tags.add("+" + prj);
                    }
                    replaceTextAtSelection(Util.join(tags, " "), true);
                }
                endOfLine++;
                textInputField.setSelection(endOfLine);
            }
            return (imeActionNext || hardwareEnterDown || hardwareEnterUp);
        }
    });

    setCloneTags(m_app.isAddTagsCloneTags());
    setWordWrap(m_app.isWordWrap());

    findViewById(R.id.cb_wrap).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setWordWrap(hasWordWrap());
        }
    });

    int textIndex = 0;
    textInputField.setSelection(textIndex);

    // Set button callbacks
    findViewById(R.id.btnContext).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showContextMenu();
        }
    });
    findViewById(R.id.btnProject).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showTagMenu();
        }
    });
    findViewById(R.id.btnPrio).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showPrioMenu();
        }
    });

    findViewById(R.id.btnDue).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            insertDate(Task.DUE_DATE);
        }
    });
    findViewById(R.id.btnThreshold).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            insertDate(Task.THRESHOLD_DATE);
        }
    });

    if (m_backup != null && m_backup.size() > 0) {
        textInputField.setSelection(textInputField.getText().length());
    }
}

From source file:org.jitsi.android.gui.call.VideoCallActivity.java

/**
 * {@inheritDoc}// w  w w .  j av a  2 s.  c om
 */
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    /**
     * The call to:
     * setVolumeControlStream(AudioManager.STREAM_VOICE_CALL)
     * doesn't work when notification was being played during this Activity
     * creation, so the buttons must be captured and the voice call level
     * will be manipulated programmatically.
     */
    int action = event.getAction();
    int keyCode = event.getKeyCode();
    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        if (action == KeyEvent.ACTION_UP) {
            volControl.onKeyVolUp();
        }
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        if (action == KeyEvent.ACTION_DOWN) {
            volControl.onKeyVolDown();
        }
        return true;
    default:
        return super.dispatchKeyEvent(event);
    }
}

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

/**
 * Display a new browser with the specified URL.
 * /*from w  ww.j a  v  a 2  s.  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 "";
}

From source file:com.jiandanbaoxian.fragment.DialogFragmentCreater.java

/**
 * Dialog ???//w  w  w. j a va 2 s.  c  o  m
 * @param mContext
 * @return
 */
private Dialog showLicenseChoiceDialog(final Context mContext) {
    View convertView = LayoutInflater.from(mContext).inflate(R.layout.dialog_license_choice, null);
    final Dialog dialog = new Dialog(mContext, R.style.mystyle);

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.layout_rule:
                if (isAgree) {
                    isAgree = false;
                    ImageView imageView = (ImageView) v.findViewById(R.id.iv_choose);
                    //                            TextView textView = (TextView)v.findViewById(R.id.tv_rule);
                    imageView.setImageResource(R.drawable.icon_choose);
                    //                            textView.setBackgroundColor(getResources().getColor(R.color.bg_gray_color_level_0));
                    //                            textView.setTextColor(getResources().getColor(R.color.tv_gray_color_level_3));
                } else {
                    isAgree = true;
                    ImageView imageView = (ImageView) v.findViewById(R.id.iv_choose);
                    //                            TextView textView = (TextView)v.findViewById(R.id.tv_rule);
                    imageView.setImageResource(R.drawable.icon_choose_selected);
                    //                            textView.setBackgroundResource(R.drawable.btn_select_base_shape_0);
                    //                            textView.setTextColor(getResources().getColor(R.color.white_color));
                }
                break;
            }
            if (onLicenseDialogClickListener != null) {
                onLicenseDialogClickListener.onClick(v, isAgree);
            }
        }
    };

    TitleBar titleBar;
    SwipeRefreshLayout swipeLayout;
    final WebView webView;
    ProgressBar progressBar;
    LinearLayout layoutRule;
    LinearLayout layoutConfirm;

    titleBar = (TitleBar) convertView.findViewById(R.id.title_bar);
    swipeLayout = (SwipeRefreshLayout) convertView.findViewById(R.id.swipe_layout);
    webView = (WebView) convertView.findViewById(R.id.webView);
    progressBar = (ProgressBar) convertView.findViewById(R.id.progress_bar);
    layoutRule = (LinearLayout) convertView.findViewById(R.id.layout_rule);
    layoutConfirm = (LinearLayout) convertView.findViewById(R.id.layout_confirm);

    WebChromeClient client = new AppChromeWebClient(titleBar, progressBar, swipeLayout);
    webView.setWebChromeClient(client);
    webView.setWebViewClient(new AppWebClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(webViewURL);
    webView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
                    webView.goBack(); //?
                    return true; //?
                }
            }
            return false;
        }
    });

    titleBar.initTitleBarInfo("", R.drawable.arrow_left, -1, "", "");
    titleBar.setOnTitleBarClickListener(new TitleBar.OnTitleBarClickListener() {
        @Override
        public void onLeftButtonClick(View v) {
            if (webView.canGoBack()) {
                webView.goBack(); //?
                return; //?
            }

            if (onLicenseDialogClickListener != null) {
                onLicenseDialogClickListener.onClick(v, isAgree);
                dismiss();
            }
        }

        @Override
        public void onRightButtonClick(View v) {

        }
    });
    UIUtils.initSwipeRefreshLayout(swipeLayout);
    swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            webView.reload();
        }
    });

    layoutConfirm.setOnClickListener(listener);
    layoutRule.setOnClickListener(listener);

    dialog.setContentView(convertView);
    dialog.getWindow().setWindowAnimations(R.style.dialog_right_control_style);
    return dialog;
}

From source file:com.android.tv.settings.accessories.AddAccessoryActivity.java

@Override
public void onNewIntent(Intent intent) {
    if (ACTION_CONNECT_INPUT.equals(intent.getAction())
            && (intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) == 0) {
        // We were the front most app and we got a new intent.
        // If screen saver is going, stop it.
        try {//from www. j  a v a 2s  .c  om
            if (mDreamManager != null && mDreamManager.isDreaming()) {
                mDreamManager.awaken();
            }
        } catch (RemoteException e) {
            // Do nothing.
        }

        KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
        if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_PAIRING) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                onHwKeyEvent(false);
            } else if (event.getAction() == KeyEvent.ACTION_DOWN) {
                onHwKeyEvent(true);
            }
        }
    } else {
        setIntent(intent);
    }
}

From source file:com.darly.im.ui.LauncherActivity.java

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    LogUtil.d(LogUtil.getLogUtilsTag(LauncherActivity.class), " onKeyDown");

    if ((event.getKeyCode() == KeyEvent.KEYCODE_BACK) && event.getAction() == KeyEvent.ACTION_UP) {
        // dismiss PlusSubMenuHelper
        if (mOverflowHelper != null && mOverflowHelper.isOverflowShowing()) {
            mOverflowHelper.dismiss();//from   w ww.  j a  va  2s .c  om
            return true;
        }
    }

    // ?menu??
    if ((event.getKeyCode() == KeyEvent.KEYCODE_BACK) && event.getAction() == KeyEvent.ACTION_DOWN) {
        doTaskToBackEvent();
    }

    try {

        return super.dispatchKeyEvent(event);
    } catch (Exception e) {
        LogUtil.e(LogUtil.getLogUtilsTag(LauncherActivity.class),
                "dispatch key event catch exception " + e.getMessage());
    }

    return false;
}

From source file:com.cloudexplorers.plugins.childBrowser.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 * /*from   w  w  w.  j a v  a2 s  .  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.setPluginsEnabled(true);
            settings.setDomStorageEnabled(true);

            webview.loadUrl(url);
            webview.setId(6);
            webview.getSettings().setLoadWithOverviewMode(true);
            webview.getSettings().setUseWideViewPort(true);
            webview.getSettings().setJavaScriptEnabled(true);
            webview.getSettings().setPluginsEnabled(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 "";
}