Example usage for android.view KeyEvent getAction

List of usage examples for android.view KeyEvent getAction

Introduction

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

Prototype

public final int getAction() 

Source Link

Document

Retrieve the action of this key event.

Usage

From source file:org.awesomeapp.messenger.ui.ConversationView.java

protected void initViews() {
    //  mStatusIcon = (ImageView) mActivity.findViewById(R.id.statusIcon);
    //   mDeliveryIcon = (ImageView) mActivity.findViewById(R.id.deliveryIcon);
    // mTitle = (TextView) mActivity.findViewById(R.id.title);
    mHistory = (RecyclerView) mActivity.findViewById(R.id.history);
    LinearLayoutManager llm = new LinearLayoutManager(mHistory.getContext());
    llm.setStackFromEnd(true);//www .j  a va2 s .c  o m
    mHistory.setLayoutManager(llm);

    mComposeMessage = (EditText) mActivity.findViewById(R.id.composeMessage);
    mSendButton = (ImageButton) mActivity.findViewById(R.id.btnSend);
    mMicButton = (ImageButton) mActivity.findViewById(R.id.btnMic);
    mButtonTalk = (TextView) mActivity.findViewById(R.id.buttonHoldToTalk);

    mButtonDeleteVoice = (ImageView) mActivity.findViewById(R.id.btnDeleteVoice);
    mViewDeleteVoice = mActivity.findViewById(R.id.viewDeleteVoice);

    mButtonDeleteVoice.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
                int resolvedColor = mHistory.getResources().getColor(android.R.color.holo_red_light);
                mButtonDeleteVoice.setBackgroundColor(resolvedColor);
            }

            return false;
        }
    });

    mButtonAttach = (ImageButton) mActivity.findViewById(R.id.btnAttach);
    mViewAttach = mActivity.findViewById(R.id.attachPanel);

    mStatusWarningView = mActivity.findViewById(R.id.warning);
    mWarningText = (TextView) mActivity.findViewById(R.id.warningText);

    mButtonAttach.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            toggleAttachMenu();
        }

    });

    mActivity.findViewById(R.id.btnAttachPicture).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mActivity.startImagePicker();
        }

    });

    mActivity.findViewById(R.id.btnTakePicture).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mActivity.startPhotoTaker();
        }

    });

    /**
    mActivity.findViewById(R.id.btnAttachFile).setOnClickListener(new View.OnClickListener() {
            
    @Override
    public void onClick(View v) {
        mActivity.startFilePicker();
    }
            
    });*/

    mActivity.findViewById(R.id.btnAttachSticker).setOnClickListener(new View.OnClickListener() {

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

    });

    mMicButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            //this is the tap to change to hold to talk mode
            if (mMicButton.getVisibility() == View.VISIBLE) {
                mComposeMessage.setVisibility(View.GONE);
                mMicButton.setVisibility(View.GONE);

                // Check if no view has focus:
                View view = mActivity.getCurrentFocus();
                if (view != null) {
                    InputMethodManager imm = (InputMethodManager) mActivity
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }

                mSendButton.setImageResource(R.drawable.ic_keyboard_black_36dp);
                mSendButton.setVisibility(View.VISIBLE);
                mButtonTalk.setVisibility(View.VISIBLE);

            }
        }

    });

    final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
        public void onLongPress(MotionEvent e) {

            //this is for recording audio directly from one press
            mActivity.startAudioRecording();

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {

            if (mActivity.isAudioRecording()) {
                boolean send = true;//inViewInBounds(mMicButton, (int) motionEvent.getX(), (int) motionEvent.getY());
                mActivity.stopAudioRecording(send);
            }

            return super.onSingleTapUp(e);
        }
    });

    mMicButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            return gestureDetector.onTouchEvent(motionEvent);

        }
    });

    mButtonTalk.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View btnTalk, MotionEvent theMotion) {
            switch (theMotion.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mActivity.startAudioRecording();
                mButtonTalk.setText(mActivity.getString(R.string.recording_release));
                mViewDeleteVoice.setVisibility(View.VISIBLE);

                break;
            case MotionEvent.ACTION_MOVE:
                boolean inBounds = inViewInBounds(btnTalk, (int) theMotion.getX(), (int) theMotion.getY());
                if (!inBounds)
                    mButtonTalk.setText(mActivity.getString(R.string.recording_delete));
                else {
                    mButtonTalk.setText(mActivity.getString(R.string.recording_release));
                    mViewDeleteVoice.setVisibility(View.VISIBLE);
                }
                break;
            case MotionEvent.ACTION_UP:
                mButtonTalk.setText(mActivity.getString(R.string.push_to_talk));
                boolean send = inViewInBounds(btnTalk, (int) theMotion.getX(), (int) theMotion.getY());
                mActivity.stopAudioRecording(send);
                mViewDeleteVoice.setVisibility(View.GONE);

                break;
            }
            return true;
        }
    });
    /**
    mHistory.setOnItemLongClickListener(new OnItemLongClickListener ()
    {
            
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            
            
     if (arg1 instanceof MessageView)
     {
            
         String textToCopy = ((MessageView)arg1).getLastMessage();
            
         int sdk = android.os.Build.VERSION.SDK_INT;
         if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
             android.text.ClipboardManager clipboard = (android.text.ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
             clipboard.setText(textToCopy); //
         } else {
             android.content.ClipboardManager clipboard = (android.content.ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
             android.content.ClipData clip = android.content.ClipData.newPlainText("chat",textToCopy);
             clipboard.setPrimaryClip(clip); //
         }
            
         Toast.makeText(mActivity, mContext.getString(R.string.toast_chat_copied_to_clipboard), Toast.LENGTH_SHORT).show();
            
         return true;
            
     }
            
        return false;
    }
            
    });**/

    mWarningText.setOnClickListener(new View.OnClickListener() {

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

    mComposeMessage.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            sendTypingStatus(true);

            return false;
        }
    });

    mComposeMessage.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {

            sendTypingStatus(hasFocus);

        }
    });

    mComposeMessage.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_CENTER:
                    sendMessage();
                    return true;

                case KeyEvent.KEYCODE_ENTER:
                    if (event.isAltPressed()) {
                        mComposeMessage.append("\n");
                        return true;
                    }
                }

            }

            return false;
        }
    });

    mComposeMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (event != null) {
                if (event.isAltPressed()) {
                    return false;
                }
            }

            InputMethodManager imm = (InputMethodManager) mContext
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null && imm.isActive(v)) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
            sendMessage();
            return true;
        }
    });

    // TODO: this is a hack to implement BUG #1611278, when dispatchKeyEvent() works with
    // the soft keyboard, we should remove this hack.
    mComposeMessage.addTextChangedListener(new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int before, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int after) {

        }

        public void afterTextChanged(Editable s) {
            doWordSearch();
            userActionDetected();
        }
    });

    mSendButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            if (mComposeMessage.getVisibility() == View.VISIBLE)
                sendMessage();
            else {
                mSendButton.setImageResource(R.drawable.ic_send_holo_light);

                if (mLastSessionStatus == SessionStatus.ENCRYPTED)
                    mSendButton.setImageResource(R.drawable.ic_send_secure);

                mSendButton.setVisibility(View.GONE);
                mButtonTalk.setVisibility(View.GONE);
                mComposeMessage.setVisibility(View.VISIBLE);
                mMicButton.setVisibility(View.VISIBLE);

            }
        }
    });

    mMessageAdapter = new ConversationRecyclerViewAdapter(mActivity, null);
    mHistory.setAdapter(mMessageAdapter);

}

From source file:net.nightwhistler.pageturner.activity.ReadingFragment.java

public boolean dispatchKeyEvent(KeyEvent event) {

    int action = event.getAction();
    int keyCode = event.getKeyCode();

    LOG.debug("Got key event: " + keyCode + " with action " + action);

    if (searchMenuItem != null && searchMenuItem.isActionViewExpanded()) {
        boolean result = searchMenuItem.getActionView().dispatchKeyEvent(event);

        if (result) {
            return true;
        }/*w  ww  .  j  av  a  2s.co m*/
    }

    final int KEYCODE_NOOK_TOUCH_BUTTON_LEFT_TOP = 92;
    final int KEYCODE_NOOK_TOUCH_BUTTON_LEFT_BOTTOM = 93;
    final int KEYCODE_NOOK_TOUCH_BUTTON_RIGHT_TOP = 94;
    final int KEYCODE_NOOK_TOUCH_BUTTON_RIGHT_BOTTOM = 95;

    boolean nook_touch_up_press = false;

    if (isAnimating() && action == KeyEvent.ACTION_DOWN) {
        stopAnimating();
        return true;
    }

    /*
     * Tricky bit of code here: if we are NOT running TTS,
     * we want to be able to start it using the play/pause button.
     * 
     * When we ARE running TTS, we'll get every media event twice:
     * once through the receiver and once here if focused. 
     * 
     * So, we only try to read media events here if tts is running.
     */
    if (!ttsIsRunning() && dispatchMediaKeyEvent(event)) {
        return true;
    }

    LOG.debug("Key event is NOT a media key event.");

    switch (keyCode) {

    case KeyEvent.KEYCODE_VOLUME_DOWN:
    case KeyEvent.KEYCODE_VOLUME_UP:
        return handleVolumeButtonEvent(event);

    case KeyEvent.KEYCODE_DPAD_RIGHT:
        if (action == KeyEvent.ACTION_DOWN) {
            pageDown(Orientation.HORIZONTAL);
        }

        return true;

    case KeyEvent.KEYCODE_DPAD_LEFT:
        if (action == KeyEvent.ACTION_DOWN) {
            pageUp(Orientation.HORIZONTAL);
        }

        return true;

    case KeyEvent.KEYCODE_BACK:
        if (action == KeyEvent.ACTION_DOWN) {

            if (titleBarLayout.getVisibility() == View.VISIBLE) {
                hideTitleBar();
                updateFromPrefs();
                return true;
            } else if (bookView.hasPrevPosition()) {
                bookView.goBackInHistory();
                return true;
            }
        }

        return false;

    case KEYCODE_NOOK_TOUCH_BUTTON_LEFT_TOP:
    case KEYCODE_NOOK_TOUCH_BUTTON_RIGHT_TOP:
        nook_touch_up_press = true;
    case KEYCODE_NOOK_TOUCH_BUTTON_LEFT_BOTTOM:
    case KEYCODE_NOOK_TOUCH_BUTTON_RIGHT_BOTTOM:
        if (!Configuration.IS_NOOK_TOUCH || action == KeyEvent.ACTION_UP)
            return false;
        if (nook_touch_up_press == config.isNookUpButtonForward())
            pageDown(Orientation.HORIZONTAL);
        else
            pageUp(Orientation.HORIZONTAL);
        return true;
    }

    LOG.debug("Not handling key event: returning false.");
    return false;
}

From source file:cn.androidy.materialdesignsample.ryanharterviewpager.ViewPager.java

/**
 * You can call this function yourself to have the scroll view perform
 * scrolling from a key event, just as if the event had been dispatched to
 * it by the view hierarchy./*  w  w w  . j  av a2 s  .  co  m*/
 *
 * @param event The key event to execute.
 * @return Return true if the event was handled, else false.
 */
public boolean executeKeyEvent(KeyEvent event) {
    boolean handled = false;
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (event.getKeyCode()) {
        case KeyEvent.KEYCODE_DPAD_LEFT:
            if (isOrientationHorizontal())
                handled = arrowScroll(FOCUS_LEFT);
            break;
        case KeyEvent.KEYCODE_DPAD_RIGHT:
            if (isOrientationHorizontal())
                handled = arrowScroll(FOCUS_RIGHT);
            break;
        case KeyEvent.KEYCODE_DPAD_UP:
            if (!isOrientationHorizontal())
                handled = arrowScroll(FOCUS_UP);
            break;
        case KeyEvent.KEYCODE_DPAD_DOWN:
            if (!isOrientationHorizontal())
                handled = arrowScroll(FOCUS_DOWN);
            break;
        case KeyEvent.KEYCODE_TAB:
            if (Build.VERSION.SDK_INT >= 11) {
                // The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD
                // before Android 3.0. Ignore the tab key on those devices.
                if (KeyEventCompat.hasNoModifiers(event)) {
                    handled = arrowScroll(FOCUS_FORWARD);
                } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {
                    handled = arrowScroll(FOCUS_BACKWARD);
                }
            }
            break;
        }
    }
    return handled;
}

From source file:net.zorgblub.typhon.fragment.ReadingFragment.java

public boolean dispatchKeyEvent(KeyEvent event) {

    int action = event.getAction();
    int keyCode = event.getKeyCode();

    LOG.debug("Got key event: " + keyCode + " with action " + action);

    if (searchMenuItem != null && MenuItemCompat.isActionViewExpanded(searchMenuItem)) {
        boolean result = MenuItemCompat.getActionView(searchMenuItem).dispatchKeyEvent(event);

        if (result) {
            return true;
        }//from   w ww .  j  av  a2 s. c  o m
    }

    final int KEYCODE_NOOK_TOUCH_BUTTON_LEFT_TOP = 92;
    final int KEYCODE_NOOK_TOUCH_BUTTON_LEFT_BOTTOM = 93;
    final int KEYCODE_NOOK_TOUCH_BUTTON_RIGHT_TOP = 94;
    final int KEYCODE_NOOK_TOUCH_BUTTON_RIGHT_BOTTOM = 95;

    boolean nook_touch_up_press = false;

    if (isAnimating() && action == KeyEvent.ACTION_DOWN) {
        stopAnimating();
        return true;
    }

    /*
       * Tricky bit of code here: if we are NOT running TTS,
     * we want to be able to start it using the play/pause button.
     *
     * When we ARE running TTS, we'll get every media event twice:
     * once through the receiver and once here if focused.
     *
     * So, we only try to read media events here if tts is running.
     */
    if (!ttsIsRunning() && dispatchMediaKeyEvent(event)) {
        return true;
    }

    LOG.debug("Key event is NOT a media key event.");

    switch (keyCode) {

    case KeyEvent.KEYCODE_VOLUME_DOWN:
    case KeyEvent.KEYCODE_VOLUME_UP:
        return handleVolumeButtonEvent(event);

    case KeyEvent.KEYCODE_DPAD_RIGHT:
        if (action == KeyEvent.ACTION_DOWN) {
            pageDown(Orientation.HORIZONTAL);
        }

        return true;

    case KeyEvent.KEYCODE_DPAD_LEFT:
        if (action == KeyEvent.ACTION_DOWN) {
            pageUp(Orientation.HORIZONTAL);
        }

        return true;

    case KeyEvent.KEYCODE_BACK:
        if (action == KeyEvent.ACTION_DOWN) {

            if (titleBarLayout.getVisibility() == View.VISIBLE) {
                hideTitleBar();
                updateFromPrefs();
                return true;
            } else if (bookView.hasPrevPosition()) {
                bookView.goBackInHistory();
                return true;
            }
        }

        return false;

    case KEYCODE_NOOK_TOUCH_BUTTON_LEFT_TOP:
    case KEYCODE_NOOK_TOUCH_BUTTON_RIGHT_TOP:
        nook_touch_up_press = true;
    case KEYCODE_NOOK_TOUCH_BUTTON_LEFT_BOTTOM:
    case KEYCODE_NOOK_TOUCH_BUTTON_RIGHT_BOTTOM:
        if (action == KeyEvent.ACTION_UP)
            return false;
        if (nook_touch_up_press == config.isNookUpButtonForward())
            pageDown(Orientation.HORIZONTAL);
        else
            pageUp(Orientation.HORIZONTAL);
        return true;
    }

    LOG.debug("Not handling key event: returning false.");
    return false;
}

From source file:com.peerless2012.twowaynestedscrollview.TwoWayNestedScrollView.java

/**
 * You can call this function yourself to have the scroll view perform
 * scrolling from a key event, just as if the event had been dispatched to
 * it by the view hierarchy.//from w ww. j  ava2  s  .  c o m
 *
 * @param event
 *            The key event to execute.
 * @return Return true if the event was handled, else false.
 */
public boolean executeKeyEvent(KeyEvent event) {
    mTempRect.setEmpty();

    if (!canVerticalScroll()) {
        if (isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            View currentFocused = findFocus();
            if (currentFocused == this)
                currentFocused = null;
            View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, View.FOCUS_DOWN);
            return nextFocused != null && nextFocused != this && nextFocused.requestFocus(View.FOCUS_DOWN);
        }
        return false;
    }
    if (!canHorizontalScroll()) {
        if (isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            View currentFocused = findFocus();
            if (currentFocused == this)
                currentFocused = null;
            View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, View.FOCUS_DOWN);
            return nextFocused != null && nextFocused != this && nextFocused.requestFocus(View.FOCUS_DOWN);
        }
        return false;
    }

    boolean handled = false;
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (event.getKeyCode()) {
        case KeyEvent.KEYCODE_DPAD_UP:
            if (!event.isAltPressed()) {
                handled = arrowScroll(View.FOCUS_UP);
            } else {
                handled = fullScroll(View.FOCUS_UP);
            }
            break;
        case KeyEvent.KEYCODE_DPAD_DOWN:
            if (!event.isAltPressed()) {
                handled = arrowScroll(View.FOCUS_DOWN);
            } else {
                handled = fullScroll(View.FOCUS_DOWN);
            }
            break;
        case KeyEvent.KEYCODE_SPACE:
            pageScroll(event.isShiftPressed() ? View.FOCUS_UP : View.FOCUS_DOWN);
            break;
        }
    }

    return handled;
}

From source file:com.aujur.ebookreader.activity.ReadingFragment.java

public boolean dispatchMediaKeyEvent(KeyEvent event) {

    int action = event.getAction();
    int keyCode = event.getKeyCode();

    if (audioManager.isMusicActive() && !ttsIsRunning()) {
        return false;
    }//from ww w  .j av  a  2  s  . c om

    switch (keyCode) {

    case KeyEvent.KEYCODE_MEDIA_PLAY:
    case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
    case KeyEvent.KEYCODE_MEDIA_PAUSE:
        return simulateButtonPress(action, R.id.playPauseButton, playPauseButton);

    case KeyEvent.KEYCODE_MEDIA_STOP:
        return simulateButtonPress(action, R.id.stopButton, stopButton);

    case KeyEvent.KEYCODE_MEDIA_NEXT:
        return simulateButtonPress(action, R.id.nextButton, nextButton);

    case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
        return simulateButtonPress(action, R.id.prevButton, prevButton);
    }

    return false;
}

From source file:android.improving.utils.views.cardsview.OrientedViewPager.java

/**
 * You can call this function yourself to have the scroll view perform
 * scrolling from a key event, just as if the event had been dispatched to
 * it by the view hierarchy.//from   w w  w.j a v  a 2 s  . com
 *
 * @param event The key event to execute.
 * @return Return true if the event was handled, else false.
 */
public boolean executeKeyEvent(KeyEvent event) {
    boolean handled = false;
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (event.getKeyCode()) {
        case KeyEvent.KEYCODE_DPAD_LEFT:
            handled = arrowScroll(FOCUS_LEFT);
            break;
        case KeyEvent.KEYCODE_DPAD_RIGHT:
            handled = arrowScroll(FOCUS_RIGHT);
            break;
        case KeyEvent.KEYCODE_TAB:
            if (Build.VERSION.SDK_INT >= 11) {
                // The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD
                // before Android 3.0. Ignore the tab key on those devices.
                if (KeyEventCompat.hasNoModifiers(event)) {
                    handled = arrowScroll(FOCUS_FORWARD);
                } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {
                    handled = arrowScroll(FOCUS_BACKWARD);
                }
            }
            break;
        }
    }
    return handled;
}

From source file:com.hippo.widget.BothScrollView.java

/**
 * You can call this function yourself to have the scroll view perform
 * scrolling from a key event, just as if the event had been dispatched to
 * it by the view hierarchy./*  w ww  .  j a v a  2s  . co  m*/
 *
 * @param event The key event to execute.
 * @return Return true if the event was handled, else false.
 */
public boolean executeKeyEvent(KeyEvent event) {
    mTempRect.setEmpty();

    if (!canScrollHorizontally()) {
        if (isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            View currentFocused = findFocus();
            if (currentFocused == this) {
                currentFocused = null;
            }
            View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, View.FOCUS_RIGHT);
            return nextFocused != null && nextFocused != this && nextFocused.requestFocus(View.FOCUS_RIGHT);
        }
        return false;
    }

    if (!canScrollVertically()) {
        if (isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            View currentFocused = findFocus();
            if (currentFocused == this) {
                currentFocused = null;
            }
            View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, View.FOCUS_DOWN);
            return nextFocused != null && nextFocused != this && nextFocused.requestFocus(View.FOCUS_DOWN);
        }
        return false;
    }

    boolean handled = false;
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (event.getKeyCode()) {
        case KeyEvent.KEYCODE_DPAD_LEFT:
            if (!event.isAltPressed()) {
                handled = arrowScrollHorizontally(View.FOCUS_LEFT);
            } else {
                handled = fullScroll(View.FOCUS_LEFT);
            }
            break;
        case KeyEvent.KEYCODE_DPAD_RIGHT:
            if (!event.isAltPressed()) {
                handled = arrowScrollHorizontally(View.FOCUS_RIGHT);
            } else {
                handled = fullScroll(View.FOCUS_RIGHT);
            }
            break;
        case KeyEvent.KEYCODE_DPAD_UP:
            if (!event.isAltPressed()) {
                handled = arrowScrollVertically(View.FOCUS_UP);
            } else {
                handled = fullScroll(View.FOCUS_UP);
            }
            break;
        case KeyEvent.KEYCODE_DPAD_DOWN:
            if (!event.isAltPressed()) {
                handled = arrowScrollVertically(View.FOCUS_DOWN);
            } else {
                handled = fullScroll(View.FOCUS_DOWN);
            }
            break;
        case KeyEvent.KEYCODE_SPACE:
            if (event.isCtrlPressed()) {
                pageScroll(event.isShiftPressed() ? View.FOCUS_LEFT : View.FOCUS_RIGHT);
            } else {
                pageScroll(event.isShiftPressed() ? View.FOCUS_UP : View.FOCUS_DOWN);
            }
            break;
        }
    }

    return handled;
}

From source file:com.guide.ViewPager.java

/**
 * You can call this function yourself to have the scroll view perform
 * scrolling from a key event, just as if the event had been dispatched to
 * it by the view hierarchy.//from  w w  w.j  ava  2s  .com
 * 
 * @param event
 *            The key event to execute.
 * @return Return true if the event was handled, else false.
 */
public boolean executeKeyEvent(KeyEvent event) {
    boolean handled = false;
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (event.getKeyCode()) {
        case KeyEvent.KEYCODE_DPAD_LEFT:
            if (isOrientationHorizontal())
                handled = arrowScroll(FOCUS_LEFT);
            break;
        case KeyEvent.KEYCODE_DPAD_RIGHT:
            if (isOrientationHorizontal())
                handled = arrowScroll(FOCUS_RIGHT);
            break;
        case KeyEvent.KEYCODE_DPAD_UP:
            if (!isOrientationHorizontal())
                handled = arrowScroll(FOCUS_UP);
            break;
        case KeyEvent.KEYCODE_DPAD_DOWN:
            if (!isOrientationHorizontal())
                handled = arrowScroll(FOCUS_DOWN);
            break;
        case KeyEvent.KEYCODE_TAB:
            if (Build.VERSION.SDK_INT >= 11) {
                // The focus finder had a bug handling FOCUS_FORWARD and
                // FOCUS_BACKWARD
                // before Android 3.0. Ignore the tab key on those devices.
                if (KeyEventCompat.hasNoModifiers(event)) {
                    handled = arrowScroll(FOCUS_FORWARD);
                } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {
                    handled = arrowScroll(FOCUS_BACKWARD);
                }
            }
            break;
        }
    }
    return handled;
}

From source file:com.android.tv.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (DEBUG)//w w w  .  j a  v a2  s  . c o  m
        Log.d(TAG, "onCreate()");
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M && !PermissionUtils.hasAccessAllEpg(this)) {
        Toast.makeText(this, R.string.msg_not_supported_device, Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    boolean skipToShowOnboarding = getIntent().getAction() == Intent.ACTION_VIEW
            && TvContract.isChannelUriForPassthroughInput(getIntent().getData());
    if (Features.ONBOARDING_EXPERIENCE.isEnabled(this) && OnboardingUtils.needToShowOnboarding(this)
            && !skipToShowOnboarding && !TvCommonUtils.isRunningInTest()) {
        // TODO: The onboarding is turned off in test, because tests are broken by the
        // onboarding. We need to enable the feature for tests later.
        startActivity(OnboardingActivity.buildIntent(this, getIntent()));
        finish();
        return;
    }

    TvApplication tvApplication = (TvApplication) getApplication();
    tvApplication.getMainActivityWrapper().onMainActivityCreated(this);
    if (BuildConfig.ENG && SystemProperties.ALLOW_STRICT_MODE.getValue()) {
        Toast.makeText(this, "Using Strict Mode for eng builds", Toast.LENGTH_SHORT).show();
    }
    mTracker = tvApplication.getTracker();
    mTvInputManagerHelper = tvApplication.getTvInputManagerHelper();
    mTvInputManagerHelper.addCallback(mTvInputCallback);
    mUsbTunerInputId = UsbTunerTvInputService.getInputId(this);
    mChannelDataManager = tvApplication.getChannelDataManager();
    mProgramDataManager = tvApplication.getProgramDataManager();
    mProgramDataManager.addOnCurrentProgramUpdatedListener(Channel.INVALID_ID,
            mOnCurrentProgramUpdatedListener);
    mProgramDataManager.setPrefetchEnabled(true);
    mChannelTuner = new ChannelTuner(mChannelDataManager, mTvInputManagerHelper);
    mChannelTuner.addListener(mChannelTunerListener);
    mChannelTuner.start();
    mPipInputManager = new PipInputManager(this, mTvInputManagerHelper, mChannelTuner);
    mPipInputManager.start();
    mMemoryManageables.add(mProgramDataManager);
    mMemoryManageables.add(ImageCache.getInstance());
    mMemoryManageables.add(TvContentRatingCache.getInstance());
    if (CommonFeatures.DVR.isEnabled(this) && BuildCompat.isAtLeastN()) {
        mDvrManager = tvApplication.getDvrManager();
        mDvrDataManager = tvApplication.getDvrDataManager();
    }

    DisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
    Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
    Point size = new Point();
    display.getSize(size);
    int screenWidth = size.x;
    int screenHeight = size.y;
    mDefaultRefreshRate = display.getRefreshRate();

    mOverlayRootView = (OverlayRootView) getLayoutInflater().inflate(R.layout.overlay_root_view, null, false);
    setContentView(R.layout.activity_tv);
    mTvView = (TunableTvView) findViewById(R.id.main_tunable_tv_view);
    int shrunkenTvViewHeight = getResources().getDimensionPixelSize(R.dimen.shrunken_tvview_height);
    mTvView.initialize((AppLayerTvView) findViewById(R.id.main_tv_view), false, screenHeight,
            shrunkenTvViewHeight);
    mTvView.setOnUnhandledInputEventListener(new OnUnhandledInputEventListener() {
        @Override
        public boolean onUnhandledInputEvent(InputEvent event) {
            if (isKeyEventBlocked()) {
                return true;
            }
            if (event instanceof KeyEvent) {
                KeyEvent keyEvent = (KeyEvent) event;
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyEvent.isLongPress()) {
                    if (onKeyLongPress(keyEvent.getKeyCode(), keyEvent)) {
                        return true;
                    }
                }
                if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
                    return onKeyUp(keyEvent.getKeyCode(), keyEvent);
                } else if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    return onKeyDown(keyEvent.getKeyCode(), keyEvent);
                }
            }
            return false;
        }
    });
    mTimeShiftManager = new TimeShiftManager(this, mTvView, mProgramDataManager, mTracker,
            new OnCurrentProgramUpdatedListener() {
                @Override
                public void onCurrentProgramUpdated(long channelId, Program program) {
                    updateMediaSession();
                    switch (mTimeShiftManager.getLastActionId()) {
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_REWIND:
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_FAST_FORWARD:
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_JUMP_TO_PREVIOUS:
                    case TimeShiftManager.TIME_SHIFT_ACTION_ID_JUMP_TO_NEXT:
                        updateChannelBannerAndShowIfNeeded(UPDATE_CHANNEL_BANNER_REASON_FORCE_SHOW);
                        break;
                    default:
                        updateChannelBannerAndShowIfNeeded(UPDATE_CHANNEL_BANNER_REASON_UPDATE_INFO);
                        break;
                    }
                }
            });

    mPipView = (TunableTvView) findViewById(R.id.pip_tunable_tv_view);
    mPipView.initialize((AppLayerTvView) findViewById(R.id.pip_tv_view), true, screenHeight,
            shrunkenTvViewHeight);

    if (!PermissionUtils.hasAccessWatchedHistory(this)) {
        WatchedHistoryManager watchedHistoryManager = new WatchedHistoryManager(getApplicationContext());
        watchedHistoryManager.start();
        mTvView.setWatchedHistoryManager(watchedHistoryManager);
    }
    mTvViewUiManager = new TvViewUiManager(this, mTvView, mPipView,
            (FrameLayout) findViewById(android.R.id.content), mTvOptionsManager);

    mPipView.setFixedSurfaceSize(screenWidth / 2, screenHeight / 2);
    mPipView.setBlockScreenType(TunableTvView.BLOCK_SCREEN_TYPE_SHRUNKEN_TV_VIEW);

    ViewGroup sceneContainer = (ViewGroup) findViewById(R.id.scene_container);
    mChannelBannerView = (ChannelBannerView) getLayoutInflater().inflate(R.layout.channel_banner,
            sceneContainer, false);
    mKeypadChannelSwitchView = (KeypadChannelSwitchView) getLayoutInflater()
            .inflate(R.layout.keypad_channel_switch, sceneContainer, false);
    InputBannerView inputBannerView = (InputBannerView) getLayoutInflater().inflate(R.layout.input_banner,
            sceneContainer, false);
    SelectInputView selectInputView = (SelectInputView) getLayoutInflater().inflate(R.layout.select_input,
            sceneContainer, false);
    selectInputView.setOnInputSelectedCallback(new OnInputSelectedCallback() {
        @Override
        public void onTunerInputSelected() {
            Channel currentChannel = mChannelTuner.getCurrentChannel();
            if (currentChannel != null && !currentChannel.isPassthrough()) {
                hideOverlays();
            } else {
                tuneToLastWatchedChannelForTunerInput();
            }
        }

        @Override
        public void onPassthroughInputSelected(TvInputInfo input) {
            Channel currentChannel = mChannelTuner.getCurrentChannel();
            String currentInputId = currentChannel == null ? null : currentChannel.getInputId();
            if (TextUtils.equals(input.getId(), currentInputId)) {
                hideOverlays();
            } else {
                tuneToChannel(Channel.createPassthroughChannel(input.getId()));
            }
        }

        private void hideOverlays() {
            getOverlayManager().hideOverlays(TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_DIALOG
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_SIDE_PANELS
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_PROGRAM_GUIDE
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_MENU
                    | TvOverlayManager.FLAG_HIDE_OVERLAYS_KEEP_FRAGMENT);
        }
    });
    mSearchFragment = new ProgramGuideSearchFragment();
    mOverlayManager = new TvOverlayManager(this, mChannelTuner, mKeypadChannelSwitchView, mChannelBannerView,
            inputBannerView, selectInputView, sceneContainer, mSearchFragment);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mAudioFocusStatus = AudioManager.AUDIOFOCUS_LOSS;

    mMediaSession = new MediaSession(this, MEDIA_SESSION_TAG);
    mMediaSession.setCallback(new MediaSession.Callback() {
        @Override
        public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
            // Consume the media button event here. Should not send it to other apps.
            return true;
        }
    });
    mMediaSession
            .setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mNowPlayingCardWidth = getResources().getDimensionPixelSize(R.dimen.notif_card_img_max_width);
    mNowPlayingCardHeight = getResources().getDimensionPixelSize(R.dimen.notif_card_img_height);

    mTvViewUiManager.restoreDisplayMode(false);
    if (!handleIntent(getIntent())) {
        finish();
        return;
    }

    mAudioCapabilitiesReceiver = new AudioCapabilitiesReceiver(this,
            new AudioCapabilitiesReceiver.OnAc3PassthroughCapabilityChangeListener() {
                @Override
                public void onAc3PassthroughCapabilityChange(boolean capability) {
                    mAc3PassthroughSupported = capability;
                }
            });
    mAudioCapabilitiesReceiver.register();

    mAccessibilityManager = (AccessibilityManager) getSystemService(Context.ACCESSIBILITY_SERVICE);
    mSendConfigInfoRecurringRunner = new RecurringRunner(this, TimeUnit.DAYS.toMillis(1),
            new SendConfigInfoRunnable(mTracker, mTvInputManagerHelper), null);
    mSendConfigInfoRecurringRunner.start();
    mChannelStatusRecurringRunner = SendChannelStatusRunnable.startChannelStatusRecurringRunner(this, mTracker,
            mChannelDataManager);

    // To avoid not updating Rating systems when changing language.
    mTvInputManagerHelper.getContentRatingsManager().update();

    initForTest();
}