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:com.flipzu.flipzu.Player.java

@Override
public void onResponseReceived(BroadcastDataSet bcast) {

    /* unset loading progress */
    setProgressBarIndeterminateVisibility(Boolean.FALSE);

    if (bcast != null) {
        debug.logV(TAG, "onResponseReceived called with bcast " + bcast.getId());
    } else {/*from   w w w  .  j av a  2s .  com*/
        debug.logV(TAG, "onResponseReceived called with bcast NULL");
    }

    boolean newBcast = false;
    if (bcast != null) {
        /* start async call to fetch user data */
        AsyncFlipInterface.getUser(bcast.getUsername(), user.getToken(), this);

        if (isNewBcast(bcast)) {
            debug.logV(TAG, "onResponseReceived, is a new broadcast");
            saveBcast(bcast);
            newBcast = true;
        } else {
            debug.logV(TAG, "onResponseReceived, is not a new broadcast");
        }
    } else {
        // try again with bcast from settings...
        if (!mSavedBcast) {
            mSavedBcast = true;
            AsyncFlipInterface.getBroadcast(getBcastFromSettings(), this);
        }
        return;
    }

    this.bcast = bcast;

    mUrl = getCurrentUrl(bcast);
    if (bcast != null) {
        mTitle = bcast.getUsername();
        if (bcast.getText() != null)
            mTitle += " - " + bcast.getText();
    }

    debug.logV(TAG, "onResponseReceived, got URL " + mUrl);

    /* layout */
    ImageView bg = (ImageView) findViewById(R.id.user_avatar);

    final TextView title_tv = (TextView) findViewById(R.id.title);
    final TextView time_tv = (TextView) findViewById(R.id.time_str);
    final TextView listeners_tv = (TextView) findViewById(R.id.listeners);
    final TextView username_tv = (TextView) findViewById(R.id.username);
    username_tv.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(Player.this, Profile.class);
            i.putExtra("user", ((TextView) findViewById(R.id.username)).getText());
            startActivity(i);
        }
    });

    bg.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(Player.this, Profile.class);
            i.putExtra("user", ((TextView) findViewById(R.id.username)).getText());
            startActivity(i);
        }
    });

    final TextView bottom_title_tv = (TextView) findViewById(R.id.player_title_bottom);

    // fix padding for player
    //      ScrollingTextView sc_tv = (ScrollingTextView) findViewById(R.id.actionbar_title);
    //      sc_tv.setPadding(35, 0, 0, 0);

    /* action bar */
    //      ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
    //      actionBar.setHomeLogo(R.drawable.logo2);

    if (bcast != null) {
        UrlImageViewHelper.setUrlDrawable(bg, bcast.getImgUrl(), R.drawable.icon_sq);
        getSupportActionBar().setTitle(bcast.getUsername());
        username_tv.setText(bcast.getUsername());
        CharSequence title = bcast.getText();
        if (title == null)
            title = getText(R.string.empty_title);
        title_tv.setText(title);
        bottom_title_tv.setText(mTitle);
        bottom_title_tv.setSelected(true); // hack to make text scroll
        if (bcast.getTimeStr() != null) {
            time_tv.setText(bcast.getTimeStr());
        }
        if (bcast.getListens() == null) {
            // maybe erased? Go back...
            Player.this.finish();
        }
        try {
            Integer listens = Integer.parseInt(bcast.getListens()) + 1;
            listeners_tv.setText(listens.toString());
        } catch (NumberFormatException e) {
            Player.this.finish();
        }
    }

    // EditText comment listener
    final EditText comment_et = (EditText) findViewById(R.id.post_comment_et);
    comment_et.setOnKeyListener(new 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
                postComment();
                return true;
            }
            return false;
        }
    });

    /* start bcast if it's a new one */
    if (newBcast) {
        debug.logV(TAG, "onResponseReceived, newBcast, sending PLAY");
        sendPlay();
    } else {
        if (mState == playerState.STOPPED)
            sendPlay();
    }

    /* stats thread */
    if (bcast != null) {
        if (bcast.getId() != null) {
            AsyncFlipInterface.getComments(Integer.parseInt(bcast.getId()), Player.this);
        }
        if (bcast.isLive()) {
            if (mState == playerState.PLAYING)
                setLiveVisible(true);
            liveHandler.removeCallbacks(mCheckLiveTask);
            liveHandler.postDelayed(mCheckLiveTask, 5000);
        } else {
            timerHandler.removeCallbacks(mTimerTask);
            timerHandler.postDelayed(mTimerTask, 1000);
        }
    }
}

From source file:com.iiordanov.bVNC.RemoteCanvasActivity.java

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

    boolean consumed = false;

    if (keyCode == KeyEvent.KEYCODE_MENU) {
        if (evt.getAction() == KeyEvent.ACTION_DOWN)
            return super.onKeyDown(keyCode, evt);
        else//from  ww  w  . ja va 2 s.  com
            return super.onKeyUp(keyCode, evt);
    }

    try {
        if (evt.getAction() == KeyEvent.ACTION_DOWN || evt.getAction() == KeyEvent.ACTION_MULTIPLE) {
            consumed = inputHandler.onKeyDown(keyCode, evt);
        } else if (evt.getAction() == KeyEvent.ACTION_UP) {
            consumed = inputHandler.onKeyUp(keyCode, evt);
        }
        resetOnScreenKeys(keyCode);
    } catch (NullPointerException e) {
    }

    return consumed;
}

From source file:android.webkit.AccessibilityInjector.java

/**
 * Attempts to handle key events when accessibility is turned on.
 *
 * @param event The key event to handle.
 * @return {@code true} if the event was handled.
 *//*  www .  j a v  a 2s  .com*/
public boolean handleKeyEventIfNecessary(KeyEvent event) {
    if (!isAccessibilityEnabled()) {
        mAccessibilityScriptInjected = false;
        toggleFallbackAccessibilityInjector(false);
        return false;
    }

    if (mAccessibilityScriptInjected) {
        // if an accessibility script is injected we delegate to it the key
        // handling. this script is a screen reader which is a fully fledged
        // solution for blind users to navigate in and interact with web
        // pages.
        if (event.getAction() == KeyEvent.ACTION_UP) {
            mWebViewClassic.sendBatchableInputMessage(EventHub.KEY_UP, 0, 0, event);
        } else if (event.getAction() == KeyEvent.ACTION_DOWN) {
            mWebViewClassic.sendBatchableInputMessage(EventHub.KEY_DOWN, 0, 0, event);
        } else {
            return false;
        }

        return true;
    }

    if (mAccessibilityInjectorFallback != null) {
        // if an accessibility injector is present (no JavaScript enabled or
        // the site opts out injecting our JavaScript screen reader) we let
        // it decide whether to act on and consume the event.
        return mAccessibilityInjectorFallback.onKeyEvent(event);
    }

    return false;
}

From source file:org.woltage.irssiconnectbot.ConsoleActivity.java

@Override
@TargetApi(11)//w  w  w  .j a va  2  s  .c  o  m
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    if (!InstallMosh.isInstallStarted()) {
        new InstallMosh(this);
    }

    configureStrictMode();
    hardKeyboard = getResources().getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY;

    hardKeyboard = hardKeyboard && !Build.MODEL.contains("Transformer");

    this.setContentView(R.layout.act_console);
    BugSenseHandler.setup(this, "d27a12dc");

    clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // hide action bar if requested by user
    try {
        ActionBar actionBar = getActionBar();
        if (!prefs.getBoolean(PreferenceConstants.ACTIONBAR, true)) {
            actionBar.hide();
        }
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
    } catch (NoSuchMethodError error) {
        Log.w(TAG, "Android sdk version pre 11. Not touching ActionBar.");
    }

    // hide status bar if requested by user
    if (prefs.getBoolean(PreferenceConstants.FULLSCREEN, false)) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    // TODO find proper way to disable volume key beep if it exists.
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    // handle requested console from incoming intent
    requested = getIntent().getData();

    inflater = LayoutInflater.from(this);

    flip = (ViewFlipper) findViewById(R.id.console_flip);
    empty = (TextView) findViewById(android.R.id.empty);

    stringPromptGroup = (RelativeLayout) findViewById(R.id.console_password_group);
    stringPromptInstructions = (TextView) findViewById(R.id.console_password_instructions);
    stringPrompt = (EditText) findViewById(R.id.console_password);
    stringPrompt.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP)
                return false;
            if (keyCode != KeyEvent.KEYCODE_ENTER)
                return false;

            // pass collected password down to current terminal
            String value = stringPrompt.getText().toString();

            PromptHelper helper = getCurrentPromptHelper();
            if (helper == null)
                return false;
            helper.setResponse(value);

            // finally clear password for next user
            stringPrompt.setText("");
            updatePromptVisible();

            return true;
        }
    });

    booleanPromptGroup = (RelativeLayout) findViewById(R.id.console_boolean_group);
    booleanPrompt = (TextView) findViewById(R.id.console_prompt);

    booleanYes = (Button) findViewById(R.id.console_prompt_yes);
    booleanYes.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            PromptHelper helper = getCurrentPromptHelper();
            if (helper == null)
                return;
            helper.setResponse(Boolean.TRUE);
            updatePromptVisible();
        }
    });

    booleanNo = (Button) findViewById(R.id.console_prompt_no);
    booleanNo.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            PromptHelper helper = getCurrentPromptHelper();
            if (helper == null)
                return;
            helper.setResponse(Boolean.FALSE);
            updatePromptVisible();
        }
    });

    // preload animations for terminal switching
    slide_left_in = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
    slide_left_out = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
    slide_right_in = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
    slide_right_out = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);

    fade_out_delayed = AnimationUtils.loadAnimation(this, R.anim.fade_out_delayed);
    fade_stay_hidden = AnimationUtils.loadAnimation(this, R.anim.fade_stay_hidden);

    // Preload animation for keyboard button
    keyboard_fade_in = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_in);
    keyboard_fade_out = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_out);

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

    final RelativeLayout keyboardGroup = (RelativeLayout) findViewById(R.id.keyboard_group);

    if (Build.MODEL.contains("Transformer")
            && getResources().getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY
            && prefs.getBoolean(PreferenceConstants.ACTIONBAR, true)) {
        keyboardGroup.setEnabled(false);
        keyboardGroup.setVisibility(View.INVISIBLE);
    }

    mKeyboardButton = (ImageView) findViewById(R.id.button_keyboard);
    mKeyboardButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return;

            inputManager.showSoftInput(flip, InputMethodManager.SHOW_FORCED);
            keyboardGroup.setVisibility(View.GONE);
        }
    });

    final ImageView symButton = (ImageView) findViewById(R.id.button_sym);
    symButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return;

            TerminalView terminal = (TerminalView) flip;

            TerminalKeyListener handler = terminal.bridge.getKeyHandler();
            handler.showCharPickerDialog(terminal);
            keyboardGroup.setVisibility(View.GONE);
        }
    });

    mInputButton = (ImageView) findViewById(R.id.button_input);
    mInputButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return;

            final TerminalView terminal = (TerminalView) flip;
            Thread promptThread = new Thread(new Runnable() {
                public void run() {
                    String inj = getCurrentPromptHelper().requestStringPrompt(null, "");
                    terminal.bridge.injectString(inj);
                }
            });
            promptThread.setName("Prompt");
            promptThread.setDaemon(true);
            promptThread.start();

            keyboardGroup.setVisibility(View.GONE);
        }
    });

    final ImageView ctrlButton = (ImageView) findViewById(R.id.button_ctrl);
    ctrlButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return;
            TerminalView terminal = (TerminalView) flip;

            TerminalKeyListener handler = terminal.bridge.getKeyHandler();
            handler.metaPress(TerminalKeyListener.META_CTRL_ON);
            terminal.bridge.tryKeyVibrate();

            keyboardGroup.setVisibility(View.GONE);
        }
    });

    final ImageView escButton = (ImageView) findViewById(R.id.button_esc);
    escButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return;
            TerminalView terminal = (TerminalView) flip;

            TerminalKeyListener handler = terminal.bridge.getKeyHandler();
            handler.sendEscape();
            terminal.bridge.tryKeyVibrate();
            keyboardGroup.setVisibility(View.GONE);
        }
    });

    // detect fling gestures to switch between terminals
    final GestureDetector detect = new GestureDetector(new ICBSimpleOnGestureListener(this));

    flip.setLongClickable(true);
    flip.setOnTouchListener(new ICBOnTouchListener(this, keyboardGroup, detect));

}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:

            String d = usernum + "-" + getStripNumber(prefs.getString(stored_chatuserNumber, "")) + "-nt";
            if (ChatSocket.socket != null) {
                ChatSocket.ps.print(d);/*from  w w  w  .  j a  v a  2  s  .c  o  m*/
            }

            Log.d("ps d onKeyDown", d + " @");

            MessageFragment.keyboard_flag = false;
            btn_emoticon_show.setImageResource(R.drawable.smily_icon);
            if (Fl_Emoticon_Holder.getVisibility() == 0) {
                Fl_Emoticon_Holder.setVisibility(FrameLayout.GONE);
            } else {
                finish();
            }
            return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

From source file:com.todoroo.astrid.activity.TaskListFragment.java

protected void setUpUiComponents() {
    // set listener for quick-changing task priority
    getListView().setOnKeyListener(new OnKeyListener() {
        @Override/*from   ww  w  .  j a  v a 2  s  . co m*/
        public boolean onKey(View view, int keyCode, KeyEvent event) {
            if (event.getAction() != KeyEvent.ACTION_UP || view == null)
                return false;

            boolean filterOn = getListView().isTextFilterEnabled();
            View selected = getListView().getSelectedView();

            // hot-key to set task priority - 1-4 or ALT + Q-R
            if (!filterOn && event.getUnicodeChar() >= '1' && event.getUnicodeChar() <= '4'
                    && selected != null) {
                int importance = event.getNumber() - '1';
                Task task = ((ViewHolder) selected.getTag()).task;
                task.setValue(Task.IMPORTANCE, importance);
                taskService.save(task);
                taskAdapter.setFieldContentsAndVisibility(selected);
            }
            // filter
            else if (!filterOn && event.getUnicodeChar() != 0) {
                getListView().setTextFilterEnabled(true);
                getListView().setFilterText(Character.toString((char) event.getUnicodeChar()));
            }
            // turn off filter if nothing is selected
            else if (filterOn && TextUtils.isEmpty(getListView().getTextFilter())) {
                getListView().setTextFilterEnabled(false);
            }

            return false;
        }
    });

    SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(getActivity());
    sortFlags = publicPrefs.getInt(SortHelper.PREF_SORT_FLAGS, 0);
    sortSort = publicPrefs.getInt(SortHelper.PREF_SORT_SORT, 0);
    sortFlags = SortHelper.setManualSort(sortFlags, isDraggable());

    getView().findViewById(R.id.progressBar).setVisibility(View.GONE);
}

From source file:com.android.talkback.SpeechController.java

/**
 * Stops the TTS engine when the Ctrl key is tapped without any other keys.
 *//*from   w ww .ja  v  a 2s  . co m*/
@Override
public boolean onKeyEvent(KeyEvent event) {
    int keyCode = event.getKeyCode();

    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        mInterruptKeyDown = (keyCode == KeyEvent.KEYCODE_CTRL_LEFT || keyCode == KeyEvent.KEYCODE_CTRL_RIGHT);
    } else if (event.getAction() == KeyEvent.ACTION_UP) {
        if (mInterruptKeyDown
                && (keyCode == KeyEvent.KEYCODE_CTRL_LEFT || keyCode == KeyEvent.KEYCODE_CTRL_RIGHT)) {
            mInterruptKeyDown = false;
            mService.interruptAllFeedback();
        }
    }

    return false;
}

From source file:com.vladstirbu.cordova.Gamepad.java

/**
 * @param cordova The context of the main Activity.
 * @param webView The associated CordovaWebView.
 *//*from   w w  w .  j a v a 2  s  . co  m*/
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
    super.initialize(cordova, webView);

    this.map.put("KEYCODE_BUTTON_A", 0);
    this.map.put("KEYCODE_BUTTON_B", 1);
    this.map.put("KEYCODE_BUTTON_Y", 3);
    this.map.put("KEYCODE_BUTTON_X", 2);
    this.map.put("KEYCODE_BUTTON_L1", 4);
    this.map.put("KEYCODE_BUTTON_R1", 5);
    this.map.put("KEYCODE_BUTTON_L2", 6);
    this.map.put("KEYCODE_BUTTON_R2", 7);
    this.map.put("KEYCODE_SPACE", 8);
    this.map.put("KEYCODE_SELECT", 8);
    this.map.put("KEYCODE_ENTER", 9);
    this.map.put("KEYCODE_START", 9);
    this.map.put("KEYCODE_BUTTON_THUMBL", 10);
    this.map.put("KEYCODE_BUTTON_THUMBR", 11);
    this.map.put("KEYCODE_DPAD_UP", 12);
    this.map.put("KEYCODE_DPAD_DOWN", 13);
    this.map.put("KEYCODE_DPAD_LEFT", 14);
    this.map.put("KEYCODE_DPAD_RIGHT", 15);
    this.map.put("KEYCODE_BACK", 16);
    this.map.put("KEYCODE_BUTTON_MODE", 16);

    this.webView.setFocusable(true);
    this.webView.setFocusableInTouchMode(true);
    this.webView.requestFocus();

    this.webView.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            //Log.v("Keyboards", String.valueOf(InputDevice.getDeviceIds().length));
            //Log.v("Input", InputDevice.getDevice(1).getName());
            //Log.v("Input", String.valueOf(InputDevice.getDevice(1).getSources()));

            //Log.v("Device id", String.valueOf(event.getDeviceId()));
            //Log.v("Source id", String.valueOf(event.getSource()));
            //Log.v("Input device", String.valueOf(InputDevice.getDevice(event.getDeviceId()).getName()));
            Log.v("KEY", String.valueOf(event.getScanCode()));
            Log.v("KEY", KeyEvent.keyCodeToString(keyCode));
            //Log.v("GamePad", String.valueOf(KeyEvent.isGamepadButton(keyCode)));

            String jsStr = jsString(keyCode, event);
            if (!jsStr.isEmpty()) {
                self.webView.sendJavascript(jsStr);
            }
            return true;
        }
    });
    this.webView.setOnGenericMotionListener(new OnGenericMotionListener() {
        public boolean onGenericMotion(View v, MotionEvent event) {
            if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
                if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    // process the joystick movement...
                    JSONObject data = new JSONObject();
                    JSONArray axes = new JSONArray();
                    try {
                        axes.put(event.getAxisValue(MotionEvent.AXIS_X));
                        axes.put(event.getAxisValue(MotionEvent.AXIS_Y));
                        axes.put(event.getAxisValue(MotionEvent.AXIS_Z));
                        axes.put(event.getAxisValue(MotionEvent.AXIS_RZ));
                        data.put("deviceId", event.getDeviceId());
                        data.put("axes", axes);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    self.webView.sendJavascript(
                            "cordova.fireWindowEvent('GamepadMotion', " + data.toString() + ");");

                    data = new JSONObject();
                    try {
                        data.put("deviceId", event.getDeviceId());
                        data.put("button", 6);
                        data.put("value", event.getAxisValue(MotionEvent.AXIS_LTRIGGER));
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    self.webView.sendJavascript(
                            "cordova.fireWindowEvent('GamepadMotion', " + data.toString() + ");");

                    data = new JSONObject();
                    try {
                        data.put("deviceId", event.getDeviceId());
                        data.put("button", 7);
                        data.put("value", event.getAxisValue(MotionEvent.AXIS_RTRIGGER));
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    self.webView.sendJavascript(
                            "cordova.fireWindowEvent('GamepadMotion', " + data.toString() + ");");

                    float hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X);
                    float hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y);
                    try {
                        data = new JSONObject();
                        data.put("deviceId", event.getDeviceId());
                        data.put("button", 14);
                        data.put("value", hatX < 0.0f);
                        self.webView.sendJavascript(
                                "cordova.fireWindowEvent('GamepadMotion', " + data.toString() + ");");
                        data = new JSONObject();
                        data.put("deviceId", event.getDeviceId());
                        data.put("button", 15);
                        data.put("value", hatX > 0.0f);
                        self.webView.sendJavascript(
                                "cordova.fireWindowEvent('GamepadMotion', " + data.toString() + ");");
                    } catch (JSONException e) {
                    }
                    try {
                        data = new JSONObject();
                        data.put("deviceId", event.getDeviceId());
                        data.put("button", 12);
                        data.put("value", hatY < 0.0f);
                        self.webView.sendJavascript(
                                "cordova.fireWindowEvent('GamepadMotion', " + data.toString() + ");");
                        data = new JSONObject();
                        data.put("deviceId", event.getDeviceId());
                        data.put("button", 13);
                        data.put("value", hatY > 0.0f);
                        self.webView.sendJavascript(
                                "cordova.fireWindowEvent('GamepadMotion', " + data.toString() + ");");
                    } catch (JSONException e) {
                    }
                }
                Log.v("MOTION", event.toString());
                return true;
            }
            return false;
        }
    });

    Log.v("GamepadButtons", "initialized");
}

From source file:com.vuze.android.remote.fragment.FilesFragment.java

public View onCreateView(android.view.LayoutInflater inflater, android.view.ViewGroup container,
        Bundle savedInstanceState) {//  ww w. j a v a 2 s .  com

    if (AndroidUtils.DEBUG) {
        Log.d(TAG, "onCreateview " + this);
    }

    View view = inflater.inflate(R.layout.frag_torrent_files, container, false);

    FragmentActivity activity = getActivity();

    progressBar = (ProgressBar) activity.findViewById(R.id.details_progress_bar);

    viewAreaToggleEditMode = view.findViewById(R.id.files_area_toggleditmode);
    tvScrollTitle = (TextView) view.findViewById(R.id.files_scrolltitle);

    btnEditMode = (CompoundButton) view.findViewById(R.id.files_editmode);
    if (btnEditMode != null) {
        btnEditMode.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (adapter == null) {
                    return;
                }
                adapter.setInEditMode(btnEditMode.isChecked());
            }
        });
    }

    final SwipeRefreshLayoutExtra swipeRefresh = (SwipeRefreshLayoutExtra) view
            .findViewById(R.id.swipe_container);
    if (swipeRefresh != null) {
        swipeRefresh.setExtraLayout(R.layout.swipe_layout_extra);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (sessionInfo == null) {
                    return;
                }
                showProgressBar();
                sessionInfo.executeRpc(new RpcExecuter() {
                    @Override
                    public void executeRpc(TransmissionRPC rpc) {
                        rpc.getTorrentFileInfo(TAG, torrentID, null, new TorrentListReceivedListener() {

                            @Override
                            public void rpcTorrentListReceived(String callID, List<?> addedTorrentMaps,
                                    List<?> removedTorrentIDs) {
                                AndroidUtils.runOnUIThread(FilesFragment.this, new Runnable() {
                                    @Override
                                    public void run() {
                                        swipeRefresh.setRefreshing(false);
                                    }
                                });
                            }
                        });
                    }
                });

            }
        });
        swipeRefresh.setOnExtraViewVisibilityChange(this);
    }

    listview = (RecyclerView) view.findViewById(R.id.files_list);
    listview.setLayoutManager(new PreCachingLayoutManager(getContext()));
    listview.setAdapter(adapter);

    listview.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            {
                if (event.getAction() != KeyEvent.ACTION_DOWN) {
                    return false;
                }
                switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_RIGHT: {
                    // expand
                    int i = adapter.getSelectedPosition();
                    FilesAdapterDisplayObject item = adapter.getItem(i);
                    if (item instanceof FilesAdapterDisplayFolder) {
                        if (!((FilesAdapterDisplayFolder) item).expand) {
                            ((FilesAdapterDisplayFolder) item).expand = true;
                            adapter.getFilter().filter("");
                            return true;
                        }
                    }
                    break;
                }

                case KeyEvent.KEYCODE_DPAD_LEFT: {
                    // collapse
                    int i = adapter.getSelectedPosition();
                    FilesAdapterDisplayObject item = adapter.getItem(i);
                    if (item instanceof FilesAdapterDisplayFolder) {
                        if (((FilesAdapterDisplayFolder) item).expand) {
                            ((FilesAdapterDisplayFolder) item).expand = false;
                            adapter.getFilter().filter("");
                            return true;
                        }
                    }
                    break;
                }

                case KeyEvent.KEYCODE_MEDIA_PLAY:
                case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: {
                    launchOrStreamFile();
                    return true;
                }
                }

                return false;
            }
        }
    });

    listview.setOnScrollListener(new RecyclerView.OnScrollListener() {
        int firstVisibleItem = 0;

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            LinearLayoutManager lm = (LinearLayoutManager) listview.getLayoutManager();
            int firstVisibleItem = lm.findFirstCompletelyVisibleItemPosition();
            if (firstVisibleItem != this.firstVisibleItem) {
                this.firstVisibleItem = firstVisibleItem;
                FilesAdapterDisplayObject itemAtPosition = adapter.getItem(firstVisibleItem);
                //               Log.d(TAG, "itemAt" + firstVisibleItem + " is " + itemAtPosition);
                //               Log.d(TAG, "tvScrollTitle=" + tvScrollTitle);
                //               Log.d(TAG, "viewAreaToggleEditMode=" + viewAreaToggleEditMode);

                if (itemAtPosition == null) {
                    return;
                }
                if (itemAtPosition.parent != null) {
                    if (viewAreaToggleEditMode != null) {
                        viewAreaToggleEditMode.setVisibility(View.GONE);
                    }
                    if (tvScrollTitle != null) {
                        tvScrollTitle.setVisibility(View.VISIBLE);
                        tvScrollTitle.setText(itemAtPosition.parent.folder);
                    }
                } else {
                    if (viewAreaToggleEditMode != null) {
                        viewAreaToggleEditMode.setVisibility(View.VISIBLE);
                    }
                    if (tvScrollTitle != null) {
                        if (viewAreaToggleEditMode != null) {
                            tvScrollTitle.setVisibility(View.INVISIBLE);
                        }
                        tvScrollTitle.setText("");
                    }
                }
            }
        }
    });

    FlexibleRecyclerSelectionListener rs = new FlexibleRecyclerSelectionListener<FilesTreeAdapter, FilesAdapterDisplayObject>() {
        @Override
        public void onItemSelected(FilesTreeAdapter adapter, final int position, boolean isChecked) {
        }

        @Override
        public void onItemClick(FilesTreeAdapter adapter, int position) {
            if (AndroidUtils.usesNavigationControl()) {
                FilesAdapterDisplayObject oItem = adapter.getItem(position);
                if (adapter.isInEditMode()) {
                    adapter.flipWant(oItem);
                    return;
                }
                if (oItem instanceof FilesAdapterDisplayFolder) {
                    FilesAdapterDisplayFolder oFolder = (FilesAdapterDisplayFolder) oItem;
                    oFolder.expand = !oFolder.expand;
                    adapter.getFilter().filter("");
                } else {
                    showFileContextMenu();
                }
            }
        }

        @Override
        public boolean onItemLongClick(FilesTreeAdapter adapter, int position) {
            if (AndroidUtils.usesNavigationControl()) {
                if (showFileContextMenu()) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public void onItemCheckedChanged(FilesTreeAdapter adapter, FilesAdapterDisplayObject item,
                boolean isChecked) {

            if (adapter.getCheckedItemCount() == 0) {
                finishActionMode();
            } else {
                // Update the subtitle with file name
                showContextualActions();
            }

            AndroidUtils.invalidateOptionsMenuHC(getActivity(), mActionMode);
        }
    };

    adapter = new FilesTreeAdapter(this.getActivity(), rs);
    adapter.setSessionInfo(sessionInfo);
    adapter.setMultiCheckModeAllowed(false);
    adapter.setCheckOnSelectedAfterMS(100);
    listview.setAdapter(adapter);

    return view;
}

From source file:org.appcelerator.titanium.view.TiUIView.java

/**
 * Registers a callback to be invoked when a hardware key is pressed in this view.
 *
 * @param v The view to have the key listener to attach to.
 *//*  w w  w  . j av  a  2 s.  c o  m*/
protected void registerForKeyPressEvents(final View v) {
    if (v == null) {
        return;
    }

    v.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View view, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                KrollDict data = new KrollDict();
                data.put(TiC.EVENT_PROPERTY_KEYCODE, keyCode);
                proxy.fireEvent(TiC.EVENT_KEY_PRESSED, data);

                switch (keyCode) {
                case KeyEvent.KEYCODE_ENTER:
                case KeyEvent.KEYCODE_DPAD_CENTER:
                    if (proxy.hasListeners(TiC.EVENT_CLICK)) {
                        proxy.fireEvent(TiC.EVENT_CLICK, null);
                        return true;
                    }
                }
            }
            return false;
        }
    });
}