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:com.duy.pascal.ui.view.console.ConsoleView.java

@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
    outAttrs.inputType = InputType.TYPE_NULL;
    //        outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE;
    return new InputConnection() {
        /**//from   w ww.ja  v a  2  s  . c  om
         * Used to handle composing text requests
         */
        private int mCursor;
        private int mComposingTextStart;
        private int mComposingTextEnd;
        private int mSelectedTextStart = 0;
        private int mSelectedTextEnd = 0;
        private boolean mInBatchEdit;

        private void sendText(CharSequence text) {
            DLog.d(TAG, "sendText: " + text);
            int n = text.length();
            for (int i = 0; i < n; i++) {
                mKeyBuffer.push(text.charAt(i));
                putString(Character.toString(text.charAt(i)));
            }
        }

        @Override
        public boolean performEditorAction(int actionCode) {
            DLog.d(TAG, "performEditorAction: " + actionCode);
            if (actionCode == EditorInfo.IME_ACTION_DONE || actionCode == EditorInfo.IME_ACTION_GO
                    || actionCode == EditorInfo.IME_ACTION_NEXT || actionCode == EditorInfo.IME_ACTION_SEND
                    || actionCode == EditorInfo.IME_ACTION_UNSPECIFIED) {
                sendText("\n");
                return true;
            }
            return false;
        }

        public boolean beginBatchEdit() {
            {
                DLog.w(TAG, "beginBatchEdit");
            }
            setImeBuffer("");
            mCursor = 0;
            mComposingTextStart = 0;
            mComposingTextEnd = 0;
            mInBatchEdit = true;
            return true;
        }

        public boolean clearMetaKeyStates(int arg0) {
            {
                DLog.w(TAG, "clearMetaKeyStates " + arg0);
            }
            return false;
        }

        public boolean commitCompletion(CompletionInfo arg0) {
            {
                DLog.w(TAG, "commitCompletion " + arg0);
            }
            return false;
        }

        @Override
        public boolean commitCorrection(CorrectionInfo correctionInfo) {
            return false;
        }

        public boolean endBatchEdit() {
            {
                DLog.w(TAG, "endBatchEdit");
            }
            mInBatchEdit = false;
            return true;
        }

        public boolean finishComposingText() {
            {
                DLog.w(TAG, "finishComposingText");
            }
            sendText(mImeBuffer);
            setImeBuffer("");
            mComposingTextStart = 0;
            mComposingTextEnd = 0;
            mCursor = 0;
            return true;
        }

        public int getCursorCapsMode(int arg0) {
            {
                DLog.w(TAG, "getCursorCapsMode(" + arg0 + ")");
            }
            return 0;
        }

        public ExtractedText getExtractedText(ExtractedTextRequest arg0, int arg1) {
            {
                DLog.w(TAG, "getExtractedText" + arg0 + "," + arg1);
            }
            return null;
        }

        public CharSequence getTextAfterCursor(int n, int flags) {
            {
                DLog.w(TAG, "getTextAfterCursor(" + n + "," + flags + ")");
            }
            int len = Math.min(n, mImeBuffer.length() - mCursor);
            if (len <= 0 || mCursor < 0 || mCursor >= mImeBuffer.length()) {
                return "";
            }
            return mImeBuffer.substring(mCursor, mCursor + len);
        }

        public CharSequence getTextBeforeCursor(int n, int flags) {
            {
                DLog.w(TAG, "getTextBeforeCursor(" + n + "," + flags + ")");
            }
            int len = Math.min(n, mCursor);
            if (len <= 0 || mCursor < 0 || mCursor >= mImeBuffer.length()) {
                return "";
            }
            return mImeBuffer.substring(mCursor - len, mCursor);
        }

        public boolean performContextMenuAction(int arg0) {
            {
                DLog.w(TAG, "performContextMenuAction" + arg0);
            }
            return true;
        }

        public boolean performPrivateCommand(String arg0, Bundle arg1) {
            {
                DLog.w(TAG, "performPrivateCommand" + arg0 + "," + arg1);
            }
            return true;
        }

        @Override
        public boolean requestCursorUpdates(int cursorUpdateMode) {
            return false;
        }

        @Override
        public Handler getHandler() {
            return null;
        }

        @Override
        public void closeConnection() {

        }

        @Override
        public boolean commitContent(@NonNull InputContentInfo inputContentInfo, int flags, Bundle opts) {
            return false;
        }

        public boolean reportFullscreenMode(boolean arg0) {
            {
                DLog.w(TAG, "reportFullscreenMode" + arg0);
            }
            return true;
        }

        public boolean commitText(CharSequence text, int newCursorPosition) {
            {
                DLog.w(TAG, "commitText(\"" + text + "\", " + newCursorPosition + ")");
            }
            char[] characters = text.toString().toCharArray();
            for (char character : characters) {
                mKeyBuffer.push(character);
            }
            clearComposingText();
            sendText(text);
            setImeBuffer("");
            mCursor = 0;
            return true;
        }

        private void clearComposingText() {
            setImeBuffer(
                    mImeBuffer.substring(0, mComposingTextStart) + mImeBuffer.substring(mComposingTextEnd));
            if (mCursor < mComposingTextStart) {
                // do nothing
            } else if (mCursor < mComposingTextEnd) {
                mCursor = mComposingTextStart;
            } else {
                mCursor -= mComposingTextEnd - mComposingTextStart;
            }
            mComposingTextEnd = mComposingTextStart = 0;
        }

        public boolean deleteSurroundingText(int leftLength, int rightLength) {
            {
                DLog.w(TAG, "deleteSurroundingText(" + leftLength + "," + rightLength + ")");
            }
            if (leftLength > 0) {
                for (int i = 0; i < leftLength; i++) {
                    sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
                }
            } else if ((leftLength == 0) && (rightLength == 0)) {
                // Delete key held down / repeating
                sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
            }
            // TODO: handle forward deletes.
            return true;
        }

        @Override
        public boolean deleteSurroundingTextInCodePoints(int beforeLength, int afterLength) {
            return false;
        }

        public boolean sendKeyEvent(KeyEvent event) {
            {
                DLog.w(TAG, "sendKeyEvent(" + event + ")");
            }
            // Some keys are sent here rather than to commitText.
            // In particular, del and the digit keys are sent here.
            // (And I have reports that the HTC Magic also sends Return here.)
            // As a bit of defensive programming, handle every key.
            dispatchKeyEvent(event);
            return true;
        }

        public boolean setComposingText(CharSequence text, int newCursorPosition) {
            {
                DLog.w(TAG, "setComposingText(\"" + text + "\", " + newCursorPosition + ")");
            }

            setImeBuffer(mImeBuffer.substring(0, mComposingTextStart) + text
                    + mImeBuffer.substring(mComposingTextEnd));
            mComposingTextEnd = mComposingTextStart + text.length();
            mCursor = newCursorPosition > 0 ? mComposingTextEnd + newCursorPosition - 1
                    : mComposingTextStart - newCursorPosition;
            return true;
        }

        public boolean setSelection(int start, int end) {
            {
                DLog.w(TAG, "setSelection" + start + "," + end);
            }
            int length = mImeBuffer.length();
            if (start == end && start > 0 && start < length) {
                mSelectedTextStart = mSelectedTextEnd = 0;
                mCursor = start;
            } else if (start < end && start > 0 && end < length) {
                mSelectedTextStart = start;
                mSelectedTextEnd = end;
                mCursor = start;
            }
            return true;
        }

        public boolean setComposingRegion(int start, int end) {
            {
                DLog.w(TAG, "setComposingRegion " + start + "," + end);
            }
            if (start < end && start > 0 && end < mImeBuffer.length()) {
                clearComposingText();
                mComposingTextStart = start;
                mComposingTextEnd = end;
            }
            return true;
        }

        public CharSequence getSelectedText(int flags) {
            try {

                {
                    DLog.w(TAG, "getSelectedText " + flags);
                }

                if (mImeBuffer.length() < 1) {
                    return "";
                }

                return mImeBuffer.substring(mSelectedTextStart, mSelectedTextEnd + 1);

            } catch (Exception ignored) {

            }

            return "";
        }

    };
}

From source file:com.owen.tvrecyclerview.widget.TvRecyclerView.java

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    boolean result = super.dispatchKeyEvent(event);
    if (!result) {
        switch (event.getAction()) {
        case KeyEvent.ACTION_DOWN:
            result = onKeyDown(event.getKeyCode(), event);
            break;
        case KeyEvent.ACTION_UP:
            result = onKeyUp(event.getKeyCode(), event);
            break;
        }/*from   w ww.  j  av  a  2s  .co  m*/
    }
    return result;
}

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 ww. j  a  va 2  s  .  c om*/
            MyApplication.getInstance().exit();
            finish();
        }
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

From source file:tk.eatheat.omnisnitch.ui.SwitchLayout.java

private synchronized void createView() {
    mView = mInflater.inflate(R.layout.recents_list_horizontal, null, false);
    mRecentListHorizontal = (HorizontalListView) mView.findViewById(R.id.recent_list_horizontal);

    mNoRecentApps = (TextView) mView.findViewById(R.id.no_recent_apps);

    mRecentListHorizontal.setSelectionListener(mSelectionGlowListener);

    mRecentListHorizontal.setOnItemClickListener(new OnItemClickListener() {
        @Override//  ww w .j a  v  a2s.co  m
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (DEBUG) {
                Log.d(TAG, "onItemClick");
            }
            TaskDescription task = mLoadedTasks.get(position);
            mRecentsManager.switchTask(task);
        }
    });

    mRecentListHorizontal.setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            if (DEBUG) {
                Log.d(TAG, "onItemLongClick");
            }
            TaskDescription task = mLoadedTasks.get(position);
            handleLongPress(task, view);
            return true;
        }
    });

    SwipeDismissHorizontalListViewTouchListener touchListener = new SwipeDismissHorizontalListViewTouchListener(
            mRecentListHorizontal, new SwipeDismissHorizontalListViewTouchListener.DismissCallbacks() {
                public void onDismiss(HorizontalListView listView, int[] reverseSortedPositions) {
                    for (int position : reverseSortedPositions) {
                        TaskDescription ad = mRecentListAdapter.getItem(position);
                        mRecentsManager.killTask(ad);
                        break;
                    }
                }

                @Override
                public boolean canDismiss(int position) {
                    return true;
                }
            });

    mRecentListHorizontal.setSwipeListener(touchListener);
    mRecentListHorizontal.setAdapter(mRecentListAdapter);

    mOpenFavorite = (ImageButton) mView.findViewById(R.id.openFavorites);

    mOpenFavorite.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            setButtonGlow(mOpenFavorite, mShowFavorites ? "arrow_up" : "arrow_down",
                    mShowFavorites ? R.drawable.arrow_up : R.drawable.arrow_down, true);

            mShowFavorites = !mShowFavorites;

            if (mConfiguration.mAnimate) {
                mFavoriteListHorizontal.startAnimation(
                        mShowFavorites ? getShowFavoriteAnimation() : getHideFavoriteAnimation());
            } else {
                mFavoriteListHorizontal.setVisibility(mShowFavorites ? View.VISIBLE : View.GONE);
                setButtonGlow(mOpenFavorite, mShowFavorites ? "arrow_up" : "arrow_down",
                        mShowFavorites ? R.drawable.arrow_up : R.drawable.arrow_down, false);
            }
        }
    });

    mFavoriteListHorizontal = (HorizontalListView) mView.findViewById(R.id.favorite_list_horizontal);

    mFavoriteListHorizontal.setSelectionListener(mSelectionGlowListener);

    mFavoriteListHorizontal.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (DEBUG) {
                Log.d(TAG, "onItemClick");
            }
            String intent = mFavoriteList.get(position);
            mRecentsManager.startIntentFromtString(intent);
        }
    });
    mFavoriteListHorizontal.setAdapter(mFavoriteListAdapter);

    mHomeButton = (GlowImageButton) mView.findViewById(R.id.home);
    mHomeButton.setOriginalImage(mContext.getResources().getDrawable(R.drawable.home));
    mHomeButton.setGlowImage(Utils.getGlowDrawable(mContext.getResources(), "home", mConfiguration.mGlowColor,
            mContext.getResources().getDrawable(R.drawable.home)));
    mHomeButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mHomeButton.setImageDrawable(mHomeButton.getGlowImage());
            }
            v.onTouchEvent(event);
            return true;
        }
    });
    mHomeButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mRecentsManager.dismissAndGoHome();
            mHomeButton.setImageDrawable(mHomeButton.getOriginalImage());
        }
    });
    mHomeButton.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toast.makeText(mContext, mContext.getResources().getString(R.string.home_help), Toast.LENGTH_SHORT)
                    .show();
            mHomeButton.setImageDrawable(mHomeButton.getOriginalImage());
            return true;
        }
    });

    mLastAppButton = (GlowImageButton) mView.findViewById(R.id.lastApp);
    mLastAppButton.setOriginalImage(mContext.getResources().getDrawable(R.drawable.lastapp));
    mLastAppButton.setGlowImage(Utils.getGlowDrawable(mContext.getResources(), "lastapp",
            mConfiguration.mGlowColor, mContext.getResources().getDrawable(R.drawable.lastapp)));
    mLastAppButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mLastAppButton.setImageDrawable(mLastAppButton.getGlowImage());
            }
            v.onTouchEvent(event);
            return true;
        }
    });

    mLastAppButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mRecentsManager.toggleLastApp();
            mLastAppButton.setImageDrawable(mLastAppButton.getOriginalImage());
        }
    });
    mLastAppButton.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toast.makeText(mContext, mContext.getResources().getString(R.string.toogle_last_app_help),
                    Toast.LENGTH_SHORT).show();
            mLastAppButton.setImageDrawable(mLastAppButton.getOriginalImage());
            return true;
        }
    });
    mKillAllButton = (GlowImageButton) mView.findViewById(R.id.killAll);
    mKillAllButton.setOriginalImage(mContext.getResources().getDrawable(R.drawable.kill_all));
    mKillAllButton.setGlowImage(Utils.getGlowDrawable(mContext.getResources(), "kill_other",
            mConfiguration.mGlowColor, mContext.getResources().getDrawable(R.drawable.kill_all)));
    mKillAllButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mKillAllButton.setImageDrawable(mKillAllButton.getGlowImage());
            }
            v.onTouchEvent(event);
            return true;
        }
    });
    mKillAllButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mRecentsManager.killAll();
            mKillAllButton.setImageDrawable(mKillAllButton.getOriginalImage());
        }
    });

    mKillAllButton.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toast.makeText(mContext, mContext.getResources().getString(R.string.kill_all_apps_help),
                    Toast.LENGTH_SHORT).show();
            mKillAllButton.setImageDrawable(mKillAllButton.getOriginalImage());
            return true;
        }
    });

    mKillOtherButton = (GlowImageButton) mView.findViewById(R.id.killOther);
    mKillOtherButton.setOriginalImage(mContext.getResources().getDrawable(R.drawable.kill_other));
    mKillOtherButton.setGlowImage(Utils.getGlowDrawable(mContext.getResources(), "kill_other",
            mConfiguration.mGlowColor, mContext.getResources().getDrawable(R.drawable.kill_other)));
    mKillOtherButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mKillOtherButton.setImageDrawable(mKillOtherButton.getGlowImage());
            }
            v.onTouchEvent(event);
            return true;
        }
    });

    mKillOtherButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mRecentsManager.killOther();
            mKillOtherButton.setImageDrawable(mKillOtherButton.getOriginalImage());
            mKillOtherButton.setImageDrawable(mKillOtherButton.getOriginalImage());
        }
    });
    mKillOtherButton.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toast.makeText(mContext, mContext.getResources().getString(R.string.kill_other_apps_help),
                    Toast.LENGTH_SHORT).show();
            mKillOtherButton.setImageDrawable(mKillOtherButton.getOriginalImage());
            return true;
        }
    });

    mSettingsButton = (GlowImageButton) mView.findViewById(R.id.settings);
    mSettingsButton.setOriginalImage(mContext.getResources().getDrawable(R.drawable.settings));
    mSettingsButton.setGlowImage(Utils.getGlowDrawable(mContext.getResources(), "settings",
            mConfiguration.mGlowColor, mContext.getResources().getDrawable(R.drawable.settings)));

    mSettingsButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mSettingsButton.setImageDrawable(mSettingsButton.getGlowImage());
            }
            v.onTouchEvent(event);
            return true;
        }
    });

    mSettingsButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent hideRecent = new Intent(SwitchService.RecentsReceiver.ACTION_HIDE_OVERLAY);
            mContext.sendBroadcast(hideRecent);

            Intent mainActivity = new Intent(mContext, SettingsActivity.class);
            mainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            mContext.startActivity(mainActivity);
            mSettingsButton.setImageDrawable(mSettingsButton.getOriginalImage());
        }
    });
    //mSettingsButton.setImageDrawable(Utils.getGlow(mContext.getResources(), "settings", mContext.getResources().getDrawable(R.drawable.settings)));
    mSettingsButton.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toast.makeText(mContext, mContext.getResources().getString(R.string.settings_help),
                    Toast.LENGTH_SHORT).show();
            mSettingsButton.setImageDrawable(mSettingsButton.getOriginalImage());
            return true;
        }
    });

    // touches inside the overlay should not hide it
    mView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (DEBUG) {
                Log.d(TAG, "mView:onTouch");
            }
            return true;
        }
    });

    mRamUsageBar = (LinearColorBar) mView.findViewById(R.id.ram_usage_bar);
    mForegroundProcessText = (TextView) mView.findViewById(R.id.foregroundText);
    mBackgroundProcessText = (TextView) mView.findViewById(R.id.backgroundText);

    mPopupView = new FrameLayout(mContext);
    try {
        mPopupView.setBackground(mContext.getResources().getDrawable(R.drawable.overlay_bg));
    } catch (NoSuchMethodError x) {
        mPopupView.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.overlay_bg));

    }
    mPopupView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (mShowing) {
                    if (DEBUG) {
                        Log.d(TAG, "mPopupView:onTouch");
                    }
                    Intent hideRecent = new Intent(SwitchService.RecentsReceiver.ACTION_HIDE_OVERLAY);
                    mContext.sendBroadcast(hideRecent);
                    return true;
                }
            }
            return false;
        }
    });
    mPopupView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (mShowing) {
                    if (DEBUG) {
                        Log.d(TAG, "onKey");
                    }
                    Intent hideRecent = new Intent(SwitchService.RecentsReceiver.ACTION_HIDE_OVERLAY);
                    mContext.sendBroadcast(hideRecent);
                    return true;
                }
            }
            return false;
        }
    });
}

From source file:com.lofland.housebot.BotController.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.housebot);// w  w w  .j a  v a2 s .  co  m
    Log.d(TAG, "onCreate");

    /*
     * TODO: If you need to maintain and pass around context:
     * http://stackoverflow.com/questions/987072/using-application-context-everywhere
     */

    // Display start up toast:
    // http://developer.android.com/guide/topics/ui/notifiers/toasts.html
    Context context = getApplicationContext();
    CharSequence text = "ex Nehilo!";
    int duration = Toast.LENGTH_SHORT;
    Toast toast = Toast.makeText(context, text, duration);
    // Display said toast
    toast.show();

    /*
     *  Turn on WiFi if it is off
     *  http://stackoverflow.com/questions/8863509/how-to-programmatically-turn-off-wifi-on-android-device
     */
    WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);

    // Prevent keyboard from popping up as soon as app launches: (it works!)
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    /*
     * Keep the screen on, because as long as we are talking to the robot, this needs to be up http://stackoverflow.com/questions/9335908/how-to- prevent-the-screen-of
     * -an-android-device-to-turn-off-during-the-execution
     */
    this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    /*
     * One or more of these three lines sets the screen to minimum brightness, Which should extend battery drain, and be less distracting on the robot.
     */
    final WindowManager.LayoutParams winParams = this.getWindow().getAttributes();
    winParams.screenBrightness = 0.01f;
    winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;

    // The "Connect" screen has a "Name" and "Address box"
    // I'm not really sure what one puts in these, and if you leave them
    // empty it works fine.
    // So not 110% sure what to do with these. Can the text just be: ""?
    // Just comment these out, and run the command with nulls?
    // mName = (EditText) findViewById(R.id.name_edit);
    // mAddress = (EditText) findViewById(R.id.address_edit);
    // The NXT Remote Control app pops up a list of seen NXTs, so maybe I
    // need to implement that instead.

    // Text to speech
    tts = new TextToSpeech(this, this);

    btnSpeak = (Button) findViewById(R.id.btnSpeak);

    txtText = (EditText) findViewById(R.id.txtSpeakText);

    // Now we need a Robot object before we an use any Roboty values!
    // We can pass defaults in or use the ones it provides
    myRobot = new Robot(INITIALTRAVELSPEED, INITIALROTATESPEED, DEFAULTVIEWANGLE);
    // We may have to pass this robot around a bit. ;)

    // Status Lines
    TextView distanceText = (TextView) findViewById(R.id.distanceText);
    distanceText.setText("???");
    TextView distanceLeftText = (TextView) findViewById(R.id.distanceLeftText);
    distanceLeftText.setText("???");
    TextView distanceRightText = (TextView) findViewById(R.id.distanceRightText);
    distanceRightText.setText("???");
    TextView headingText = (TextView) findViewById(R.id.headingText);
    headingText.setText("???");
    TextView actionText = (TextView) findViewById(R.id.isDoingText);
    actionText.setText("None");

    // Travel speed slider bar
    SeekBar travelSpeedBar = (SeekBar) findViewById(R.id.travelSpeed_seekBar);
    travelSpeedBar.setProgress(myRobot.getTravelSpeed());
    travelSpeedBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setTravelSpeed(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    // View angle slider bar
    SeekBar viewAngleBar = (SeekBar) findViewById(R.id.viewAngle_seekBar);
    viewAngleBar.setProgress(myRobot.getViewAngle());
    viewAngleBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setViewAngle(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            Log.d(TAG, "View Angle Slider ");
            /*
             * If this gets sent every few milliseconds with the normal output, then there is no need to send a specific command every time it changes!
             */
            // sendCommandToRobot(Command.VIEWANGLE);
        }
    });

    // Rotation speed slider bar speedSP_seekBar
    SeekBar rotateSpeedBar = (SeekBar) findViewById(R.id.rotateSpeed_seekBar);
    rotateSpeedBar.setProgress(myRobot.getRotateSpeed());
    rotateSpeedBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setRotateSpeed(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    /*
     * This is where we find the four direction buttons defined So we could define ALL buttons this way, set up an ENUM with all options, and call the same function for ALL
     * options!
     * 
     * Just be sure the "release" only stops the robot on these, and not every button on the screen.
     * 
     * Maybe see how the code I stole this form does it?
     */
    Button buttonUp = (Button) findViewById(R.id.forward_button);
    buttonUp.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.FORWARD));
    Button buttonDown = (Button) findViewById(R.id.reverse_button);
    buttonDown.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.REVERSE));
    Button buttonLeft = (Button) findViewById(R.id.left_button);
    buttonLeft.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.LEFT));
    Button buttonRight = (Button) findViewById(R.id.right_button);
    buttonRight.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.RIGHT));

    // button on click event
    btnSpeak.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            speakOut();
        }

    });

    /*
     * This causes the typed text to be spoken when the Enter key is pressed.
     */
    txtText.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)) {
                // Perform action on key press
                // Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
                speakOut();
                return true;
            }
            return false;
        }
    });

    // Connect button
    connectToggleButton = (ToggleButton) findViewById(R.id.connectToggleButton);
    connectToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                // The toggle is enabled
                Log.d(TAG, "Connect button Toggled On!");
                myRobot.setConnectRequested(true);
            } else {
                // The toggle is disabled
                Log.d(TAG, "Connect button Toggled OFF.");
                myRobot.setConnectRequested(false);
            }
        }
    });

    if (nxtStatusMessageHandler == null)
        nxtStatusMessageHandler = new StatusMessageHandler();

    mStatusThread = new StatusThread(context, nxtStatusMessageHandler);
    mStatusThread.start();

    // Start the web service!
    Log.d(TAG, "Start web service here:");
    // Initiate message handler for web service
    if (robotWebServerMessageHandler == null)
        robotWebServerMessageHandler = new WebServerMessageHandler(this); // Has to include "this" to send context, see WebServerMessageHandler for explanation

    robotWebServer = new WebServer(context, PORT, robotWebServerMessageHandler, myRobot);

    try {
        robotWebServer.start();
    } catch (IOException e) {
        Log.d(TAG, "robotWebServer failed to start");
        //e.printStackTrace();
    }

    // TODO:
    /*
     * See this reference on how to rebuild this handler in onCreate if it is gone: http://stackoverflow.com/questions/18221593/android-handler-changing-weakreference
     */
    // TODO - Should I stop this thread in Destroy or some such place?

    Log.d(TAG, "Web service was started.");

}

From source file:com.fvd.nimbus.PaintActivity.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) {
            drawView.zoom(1.25f);/*from w w w .  j  a  va  2  s. c o  m*/
        }
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        if (action == KeyEvent.ACTION_DOWN) {
            drawView.zoom(0.75f);
        }
        return true;
    case KeyEvent.KEYCODE_BACK:
        if (action == KeyEvent.ACTION_DOWN) {
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
                return true;
            } else if (findViewById(R.id.text_field).getVisibility() != View.GONE) {
                findViewById(R.id.text_field).setVisibility(View.GONE);
                drawView.hideCrop();
                drawView.startEdit();
                setSelectedFoot(0);
                return true;
            } else if (findViewById(R.id.color_menu).getVisibility() != View.GONE) {
                findViewById(R.id.color_menu).setVisibility(View.GONE);
                drawView.hideCrop();
                drawView.startEdit();
                setSelectedFoot(0);
                return true;
            } else if (findViewById(R.id.draw_tools).getVisibility() != View.GONE) {
                findViewById(R.id.draw_tools).setVisibility(View.GONE);
                drawView.hideCrop();
                drawView.startEdit();
                setSelectedFoot(0);
                return false;
            } else if (!drawView.hideCrop()) {
                if (!saved && storePath.length() == 0)
                    showDialog(0);
                else {
                    drawView.recycle();
                    finish();
                    return true;
                }
            } else {
                ((ImageButton) findViewById(R.id.bToolCrop)).setSelected(false);
                drawView.startEdit();
                setSelectedFoot(0);
                return true;
            }

        }
    default:
        return super.dispatchKeyEvent(event);
    }
}

From source file:org.petero.droidfish.activities.EditBoard.java

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case EDIT_DIALOG: {
        final int SIDE_TO_MOVE = 0;
        final int CLEAR_BOARD = 1;
        final int INITIAL_POS = 2;
        final int CASTLING_FLAGS = 3;
        final int EN_PASSANT_FILE = 4;
        final int MOVE_COUNTERS = 5;
        final int COPY_POSITION = 6;
        final int PASTE_POSITION = 7;
        final int GET_FEN = 8;

        List<CharSequence> lst = new ArrayList<CharSequence>();
        List<Integer> actions = new ArrayList<Integer>();
        lst.add(getString(R.string.side_to_move));
        actions.add(SIDE_TO_MOVE);/*from www.  j av  a  2  s .  co m*/
        lst.add(getString(R.string.clear_board));
        actions.add(CLEAR_BOARD);
        lst.add(getString(R.string.initial_position));
        actions.add(INITIAL_POS);
        lst.add(getString(R.string.castling_flags));
        actions.add(CASTLING_FLAGS);
        lst.add(getString(R.string.en_passant_file));
        actions.add(EN_PASSANT_FILE);
        lst.add(getString(R.string.move_counters));
        actions.add(MOVE_COUNTERS);
        lst.add(getString(R.string.copy_position));
        actions.add(COPY_POSITION);
        lst.add(getString(R.string.paste_position));
        actions.add(PASTE_POSITION);
        if (DroidFish.hasFenProvider(getPackageManager())) {
            lst.add(getString(R.string.get_fen));
            actions.add(GET_FEN);
        }
        final List<Integer> finalActions = actions;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.edit_board);
        builder.setItems(lst.toArray(new CharSequence[lst.size()]), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                switch (finalActions.get(item)) {
                case SIDE_TO_MOVE:
                    showDialog(SIDE_DIALOG);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                case CLEAR_BOARD: {
                    Position pos = new Position();
                    cb.setPosition(pos);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                }
                case INITIAL_POS: {
                    try {
                        Position pos = TextIO.readFEN(TextIO.startPosFEN);
                        cb.setPosition(pos);
                        setSelection(-1);
                        checkValidAndUpdateMaterialDiff();
                    } catch (ChessParseError e) {
                    }
                    break;
                }
                case CASTLING_FLAGS:
                    removeDialog(CASTLE_DIALOG);
                    showDialog(CASTLE_DIALOG);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                case EN_PASSANT_FILE:
                    removeDialog(EP_DIALOG);
                    showDialog(EP_DIALOG);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                case MOVE_COUNTERS:
                    removeDialog(MOVCNT_DIALOG);
                    showDialog(MOVCNT_DIALOG);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                case COPY_POSITION: {
                    setPosFields();
                    String fen = TextIO.toFEN(cb.pos) + "\n";
                    ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    clipboard.setText(fen);
                    setSelection(-1);
                    break;
                }
                case PASTE_POSITION: {
                    ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    if (clipboard.hasText()) {
                        String fen = clipboard.getText().toString();
                        setFEN(fen);
                    }
                    break;
                }
                case GET_FEN:
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.setType("application/x-chess-fen");
                    try {
                        startActivityForResult(i, RESULT_GET_FEN);
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
        AlertDialog alert = builder.create();
        return alert;
    }
    case SIDE_DIALOG: {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.select_side_to_move_first);
        final int selectedItem = (cb.pos.whiteMove) ? 0 : 1;
        builder.setSingleChoiceItems(new String[] { getString(R.string.white), getString(R.string.black) },
                selectedItem, new Dialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        if (id == 0) { // white to move
                            cb.pos.setWhiteMove(true);
                            checkValidAndUpdateMaterialDiff();
                            dialog.cancel();
                        } else {
                            cb.pos.setWhiteMove(false);
                            checkValidAndUpdateMaterialDiff();
                            dialog.cancel();
                        }
                    }
                });
        AlertDialog alert = builder.create();
        return alert;
    }
    case CASTLE_DIALOG: {
        final CharSequence[] items = { getString(R.string.white_king_castle),
                getString(R.string.white_queen_castle), getString(R.string.black_king_castle),
                getString(R.string.black_queen_castle) };
        boolean[] checkedItems = { cb.pos.h1Castle(), cb.pos.a1Castle(), cb.pos.h8Castle(), cb.pos.a8Castle() };
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.castling_flags);
        builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                Position pos = new Position(cb.pos);
                boolean a1Castle = pos.a1Castle();
                boolean h1Castle = pos.h1Castle();
                boolean a8Castle = pos.a8Castle();
                boolean h8Castle = pos.h8Castle();
                switch (which) {
                case 0:
                    h1Castle = isChecked;
                    break;
                case 1:
                    a1Castle = isChecked;
                    break;
                case 2:
                    h8Castle = isChecked;
                    break;
                case 3:
                    a8Castle = isChecked;
                    break;
                }
                int castleMask = 0;
                if (a1Castle)
                    castleMask |= 1 << Position.A1_CASTLE;
                if (h1Castle)
                    castleMask |= 1 << Position.H1_CASTLE;
                if (a8Castle)
                    castleMask |= 1 << Position.A8_CASTLE;
                if (h8Castle)
                    castleMask |= 1 << Position.H8_CASTLE;
                pos.setCastleMask(castleMask);
                cb.setPosition(pos);
                checkValidAndUpdateMaterialDiff();
            }
        });
        AlertDialog alert = builder.create();
        return alert;
    }
    case EP_DIALOG: {
        final CharSequence[] items = { "A", "B", "C", "D", "E", "F", "G", "H", getString(R.string.none) };
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.select_en_passant_file);
        builder.setSingleChoiceItems(items, getEPFile(), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                setEPFile(item);
                dialog.cancel();
            }
        });
        AlertDialog alert = builder.create();
        return alert;
    }
    case MOVCNT_DIALOG: {
        View content = View.inflate(this, R.layout.edit_move_counters, null);
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setView(content);
        builder.setTitle(R.string.edit_move_counters);
        final EditText halfMoveClock = (EditText) content.findViewById(R.id.ed_cnt_halfmove);
        final EditText fullMoveCounter = (EditText) content.findViewById(R.id.ed_cnt_fullmove);
        halfMoveClock.setText(String.format(Locale.US, "%d", cb.pos.halfMoveClock));
        fullMoveCounter.setText(String.format(Locale.US, "%d", cb.pos.fullMoveCounter));
        final Runnable setCounters = new Runnable() {
            public void run() {
                try {
                    int halfClock = Integer.parseInt(halfMoveClock.getText().toString());
                    int fullCount = Integer.parseInt(fullMoveCounter.getText().toString());
                    cb.pos.halfMoveClock = halfClock;
                    cb.pos.fullMoveCounter = fullCount;
                } catch (NumberFormatException nfe) {
                    Toast.makeText(getApplicationContext(), R.string.invalid_number_format, Toast.LENGTH_SHORT)
                            .show();
                }
            }
        };
        builder.setPositiveButton("Ok", new Dialog.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                setCounters.run();
            }
        });
        builder.setNegativeButton("Cancel", null);

        final Dialog dialog = builder.create();

        fullMoveCounter.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    setCounters.run();
                    dialog.cancel();
                    return true;
                }
                return false;
            }
        });
        return dialog;
    }
    }
    return null;
}

From source file:com.neka.cordova.inappbrowser.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject//from  w w w. ja v a2 s .c o m
 */
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // 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 InAppBrowserDialog(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.setInAppBroswer(getInAppBrowser());

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

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            //Please, no more black! 
            toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_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
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            /*
            back.setText("<");
            */
            Resources activityRes = cordova.getActivity().getResources();
            int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable backIcon = activityRes.getDrawable(backResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                back.setBackgroundDrawable(backIcon);
            } else {
                back.setBackground(backIcon);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            //forward.setText(">");
            int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable fwdIcon = activityRes.getDrawable(fwdResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                forward.setBackgroundDrawable(fwdIcon);
            } else {
                forward.setBackground(fwdIcon);
            }
            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.MATCH_PARENT, LayoutParams.MATCH_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
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            //close.setText(buttonLabel);
            int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable closeIcon = activityRes.getDrawable(closeResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                close.setBackgroundDrawable(closeIcon);
            } else {
                close.setBackground(closeIcon);
            }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new WebView(cordova.getActivity());
            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginState(android.webkit.WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                CookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                CookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.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(inAppWebView);

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

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.dtworkshop.inappcrossbrowser.WebViewBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 *//* w  ww . j a  v a  2s .  c o m*/
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // 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;
        }

        @SuppressLint("NewApi")
        public void run() {
            // Let's create the main dialog
            dialog = new InAppBrowserDialog(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.setInAppBroswer(getInAppBrowser());

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

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            //Please, no more black!
            toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_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
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            Resources activityRes = cordova.getActivity().getResources();
            int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable backIcon = activityRes.getDrawable(backResId);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                back.setBackgroundDrawable(backIcon);
            } else {
                back.setBackground(backIcon);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable fwdIcon = activityRes.getDrawable(fwdResId);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                forward.setBackgroundDrawable(fwdIcon);
            } else {
                forward.setBackground(fwdIcon);
            }
            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.MATCH_PARENT, LayoutParams.MATCH_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/Done button
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable closeIcon = activityRes.getDrawable(closeResId);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                close.setBackgroundDrawable(closeIcon);
            } else {
                close.setBackground(closeIcon);
            }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new WebView(cordova.getActivity());
            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginState(WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                CookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                CookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.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(inAppWebView);

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

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:net.bluecarrot.lite.MainActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
            if (webViewFacebook.canGoBack()) {
                webViewFacebook.goBack();
            } else {
                // exit
                finish();/*from  w  w w.  j av a  2  s.c om*/
            }
            return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}