Example usage for android.view GestureDetector GestureDetector

List of usage examples for android.view GestureDetector GestureDetector

Introduction

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

Prototype

@Deprecated
public GestureDetector(OnGestureListener listener) 

Source Link

Document

Creates a GestureDetector with the supplied listener.

Usage

From source file:com.mitre.holdshort.MainActivity.java

private void startMainActivity() {

    // Set screen layout
    setContentView(R.layout.main);/* www  . j av  a  2s.  c  o  m*/
    imageHelper = new ImageHelper();
    summaryGestureDetector = new GestureDetector(new summaryGester());

    // Get Reference to Shared Preferences file
    auralAlerts = settings.getBoolean("auralAlerts", true);
    settings.edit().putBoolean("auralAlerts", auralAlerts);
    announceRWY = settings.getBoolean("announceRWY", true);
    settings.edit().putBoolean("announceRWY", announceRWY);

    // Airport ID
    airportID = (TextView) findViewById(R.id.airportID);
    airportID.setText("K" + airport);

    // SpeechButton
    speechBtn = (ImageView) findViewById(R.id.speechBtn);
    speechBtn.setOnClickListener(speechBtnClickListener);

    // Get open close button
    openClose = (TextView) findViewById(R.id.openClose);
    openClose.setText("close");
    // openClose.setTextColor(Color.argb(200, 255, 255, 255));
    openClose.setOnClickListener(openCloseListener);

    // departure runway button
    depRwyBtn = (TextView) findViewById(R.id.depRwyBtn);
    depRwyBtn.setOnClickListener(depRwyListener);
    depRwyBtn.setText("Departure Rwy");
    depRwyBtn.setBackgroundResource(R.drawable.hatched_small_bg_layer);
    depRwyBtn.setPadding(10, 5, 10, 5);

    // info button - used to start prefs activity
    infoBtn = (ImageButton) findViewById(R.id.info_btn);
    // infoBtn.setBackgroundColor(Color.rgb(0,0,0));
    infoBtn.setOnClickListener(settingsMenuListener);

    // taxi button - used to start Taxi instruction activity
    taxiBtn = (ImageButton) findViewById(R.id.taxi_btn);
    // taxiBtn.setBackgroundColor(Color.rgb(0,0,0));
    taxiBtn.setOnClickListener(taxiBtnListener);

    // summary info - when drawer is closed
    summaryBar = (RelativeLayout) findViewById(R.id.summaryBar);
    summaryBar.setOnTouchListener(summaryTouchListener);
    runwayContainer = (LinearLayout) findViewById(R.id.holder);
    innerHolder = (LinearLayout) findViewById(R.id.innerHolder);
    slidingPanel = (SlidingPanel) findViewById(R.id.slidingDrawer);

    // header
    header = (RelativeLayout) findViewById(R.id.header);
    headerDropShadow = (View) findViewById(R.id.header_drop_shadow);
    slidingPanel.setHeaderDropShadow(headerDropShadow);
    slidingPanel.setRunwayContainer(runwayContainer);
    slidingPanel.setOpenCloseTextView(openClose);
    slidingPanel.setHandler(this.handler);

    summaryInfo = (RelativeLayout) findViewById(R.id.summary_info);
    summary_index = (TextView) findViewById(R.id.summary_index);
    summary_thumb = (TextView) findViewById(R.id.summary_thumb);
    summary_thumb.setWidth(90);

    // Taxi path area
    taxiClearance = (TextView) findViewById(R.id.taxiClearance);
    taxiClearance.setTextSize(12);
    taxiClearance.setPadding(5, 0, 5, 0);
    taxiClearance.setTextColor(Color.WHITE);
    // taxiClearance.setBackgroundColor(Color.rgb(0,0,0));
    taxiClearance.setOnClickListener(taxiPathListener);

    // Airport Diagram
    plateView = (AirportPlateView) findViewById(R.id.plateView);
    // Set up the nav control for the moving map
    // this is used when ownship is off screen
    navControl = (ImageView) findViewById(R.id.showNavBtn);
    plateView.setNavControls(navControl);
    navControl.setVisibility(ImageView.INVISIBLE);
    navControl.setOnClickListener(navControlListener);

    // // Lat/Lon Ref 1 SFO
    Point latLon1 = new Point(37.627827, -122.366794);
    Point latLon2 = new Point(37.606827, -122.380724);
    XYPoint xy1 = new XYPoint(134, 173);
    XYPoint xy2 = new XYPoint(340, 281);

    // Lat/Lon Ref 1 HEF
    // Point latLon1 = new Point(38.727680,-77.518803);
    // Point latLon2 = new Point(38.714041,-77.508976);
    // XYPoint xy1 = new XYPoint(140,187);
    // XYPoint xy2 = new XYPoint(322,513);
    plateView.geoReference(latLon1, latLon2, xy1, xy2);

    Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    plateView.updatePosition(loc.getBearing(), loc.getLatitude(), loc.getLongitude());

    // navView.setScroll(plateView);
    TextView emptyPlate = (TextView) findViewById(R.id.emptyPlate);

    if (!(plateView.setImage(airport))) {
        // Place holder if no plate is available
        emptyPlate.setVisibility(View.VISIBLE);
        plateView.setVisibility(View.GONE);

    } else {
        // Show plate. Hide placeholder
        plateView.setImage(airport);
        emptyPlate.setVisibility(View.GONE);
    }

    // Create logger for alerts
    alertLogger = new AlertLogger(airport, MainActivity.this);

    // Alert Panels
    alertScreen = (RelativeLayout) findViewById(R.id.alertScreen);
    betaControls = (LinearLayout) findViewById(R.id.betaControls);
    goodAlert = (TextView) findViewById(R.id.goodAlert);
    goodAlert.setOnClickListener(alertResponseListener);
    badAlert = (TextView) findViewById(R.id.badAlert);
    badAlert.setOnClickListener(alertResponseListener);
    lateAlert = (TextView) findViewById(R.id.lateAlert);
    lateAlert.setOnClickListener(alertResponseListener);
    earlyAlert = (TextView) findViewById(R.id.earlyAlert);
    earlyAlert.setOnClickListener(alertResponseListener);

    miniAlert = (TextView) findViewById(R.id.miniAlertText);
    miniAlert.setOnClickListener(maximizeAlert);

    holdShort = (LinearLayout) findViewById(R.id.holdShort);
    holdShort.getChildAt(0).setBackgroundDrawable(imageHelper
            .getRoundedCornerBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.alert), 10));
    holdShort.setOnClickListener(minimizeAlert);
    noClearance = (LinearLayout) findViewById(R.id.noClearance);
    noClearance.setOnClickListener(minimizeAlert);
    noClearance.getChildAt(0).setBackgroundDrawable(imageHelper
            .getRoundedCornerBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.alert), 10));
    crossingAlert = (LinearLayout) findViewById(R.id.crossingAlert);
    noTakeoffClearance = (LinearLayout) findViewById(R.id.noTakeoffClearance);
    noTakeoffClearance.getChildAt(0).setBackgroundDrawable(imageHelper
            .getRoundedCornerBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.alert), 10));
    noTakeoffClearance.setOnClickListener(minimizeAlert);
    disabled_gps = (LinearLayout) findViewById(R.id.disabled_gps);
    disabled_gps.getChildAt(0).setBackgroundDrawable(imageHelper
            .getRoundedCornerBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.disabled), 10));
    disabled_gps.setOnClickListener(minimizeAlert);

    disabled_speed = (LinearLayout) findViewById(R.id.disabled_speed);
    disabled_speed.getChildAt(0).setBackgroundDrawable(imageHelper
            .getRoundedCornerBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.disabled), 10));
    disabled_speed.setOnClickListener(minimizeAlert);

    // Instantiate media player & set completion listener
    mp = new MediaPlayer();
    mp.setOnCompletionListener(alertPlaybackListener);

    // Instruction List instantiation
    instructionList = new ArrayList<String>();

    setUpRunways();
    slidingPanel.setOnTouchListener(summaryTouchListener);
    // Instantiate Alert Manager
    alertManager = new AlertManager(rwyMgr);

    allSetUp = true;
}

From source file:net.homelinux.penecoptero.android.citybikes.app.MainActivity.java

protected void applyMapViewLongPressListener(MapView mapView) {
    final MapView finalMapView = mapView;

    final GestureDetector gd = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
        @Override/*from www .j  av a2  s  .c  o  m*/
        public void onLongPress(MotionEvent e) {
            //Log.i("CityBikes","LONG PRESS!");
            Projection astral = finalMapView.getProjection();
            GeoPoint center = astral.fromPixels((int) e.getX(), (int) e.getY());
            locator.lockCenter(center);
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            // TODO Auto-generated method stub
            //Log.i("CityBikes","Double tap!");
            Projection astral = finalMapView.getProjection();
            GeoPoint center = astral.fromPixels((int) e.getX(), (int) e.getY());
            locator.lockCenter(center);
            return super.onDoubleTap(e);
        }

    });
    mapView.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent ev) {
            return gd.onTouchEvent(ev);
        }
    });
}

From source file:org.transdroid.gui.TorrentsFragment.java

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

    // Attach the Android TLog to the daemon logger
    DLog.setLogger(TLog.getInstance());/*  www . j av  a2s. c  om*/

    // Set activity screen features
    useTabletInterface = Transdroid.isTablet(getResources());
    registerForContextMenu(getListView());
    getListView().setTextFilterEnabled(true);
    getListView().setOnItemClickListener(onTorrentClicked);

    // Access UI widgets and title
    emptyText = (TextView) findViewById(android.R.id.empty);
    startsettings = (LinearLayout) findViewById(R.id.startsettings);
    taskmessage = (TextView) findViewById(R.id.taskmessage);
    statusBox = (TableLayout) findViewById(R.id.st_box);
    statusDown = (TextView) findViewById(R.id.st_down);
    statusDownRate = (TextView) findViewById(R.id.st_downrate);
    statusUp = (TextView) findViewById(R.id.st_up);
    statusUpRate = (TextView) findViewById(R.id.st_uprate);
    setProgressBar(false);

    // Open settings button
    Button startsettingsButton = (Button) findViewById(R.id.startsettings_button);
    startsettingsButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // Open settings screen
            startActivityForResult(new Intent(getActivity(), PreferencesMain.class), ACTIVITY_PREFERENCES);
        }
    });
    // Show a dialog allowing control over max. upload and download speeds
    statusBox.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(DIALOG_RATES);
        }
    });

    // The control bar and view type selector (quickaction popup)
    controlbar = (LinearLayout) findViewById(R.id.controlbar);
    viewtype = (TextView) findViewById(R.id.viewtype);
    viewtypeselector = (ImageView) findViewById(R.id.viewtypeselector);
    viewtypeselectorpopup = new TorrentViewSelectorWindow(viewtypeselector,
            new MainViewTypeSelectionListener() {
                @Override
                public void onMainViewTypeSelected(MainViewType newType) {
                    if (activeMainView != newType) {
                        // Show torrents for the new main view selection
                        activeMainView = newType;
                        updateTorrentsView(true);
                    }
                }
            }, new LabelSelectionListener() {
                @Override
                public void onLabelSelected(int labelPosition) {
                    String newLabel = availableLabels.get(labelPosition);
                    if (activeLabel != newLabel) {
                        // Show torrents for the new label selection
                        activeLabel = newLabel;
                        updateTorrentsView(true);
                    }
                }
            });
    viewtypeselector.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            viewtypeselectorpopup.showLikePopDownMenu();
        }
    });

    // Swiping (flinging) between server configurations (or labels)
    gestureDetector = new GestureDetector(new MainScreenGestureListener());
    getListView().setOnTouchListener(this);
    emptyText.setOnTouchListener(this);

    // Attach auto refresh handler
    handler = new Handler();
    refreshRunable = new Runnable() {
        public void run() {
            updateTorrentList();
            setupRefreshTimer();
        }
    };

    // Read all the user preferences
    readSettings();

    // Setup the default server daemon
    setupDaemon();

    // Set up a task queue
    queue = new TaskQueue(new TaskResultHandler(this));
    queue.start();

    // Start the alarm service, if needed
    BootReceiver.startAlarm(getActivity().getApplicationContext());

    // Check for new app version, if needed
    BootReceiver.startUpdateCheck(getActivity().getApplicationContext());

    handleIntent(getActivity().getIntent());

}

From source file:org.connectbot.ConsoleFragment.java

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

    this.inflater = inflater;

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

    stringPromptGroup = (RelativeLayout) v.findViewById(R.id.console_password_group);
    stringPromptInstructions = (TextView) v.findViewById(R.id.console_password_instructions);
    stringPrompt = (EditText) v.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);/*from  ww w  .  j a v  a  2s. c  om*/

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

            return true;
        }
    });

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

    booleanYes = (Button) v.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) v.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(getActivity(), R.anim.slide_left_in);
    slide_left_out = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_left_out);
    slide_right_in = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_right_in);
    slide_right_out = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_right_out);

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

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

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

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

    mKeyboardButton = (ImageView) v.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 ctrlButton = (ImageView) v.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);

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

    final ImageView escButton = (ImageView) v.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();

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

    // detect fling gestures to switch between terminals
    final GestureDetector detect = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
        private float totalY = 0;

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

            final float distx = e2.getRawX() - e1.getRawX();
            final float disty = e2.getRawY() - e1.getRawY();
            final int goalwidth = flip.getWidth() / 2;

            // need to slide across half of display to trigger console change
            // make sure user kept a steady hand horizontally
            if (Math.abs(disty) < (flip.getHeight() / 4)) {
                if (distx > goalwidth) {
                    shiftCurrentTerminal(SHIFT_RIGHT);
                    return true;
                }

                if (distx < -goalwidth) {
                    shiftCurrentTerminal(SHIFT_LEFT);
                    return true;
                }

            }

            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

            // if copying, then ignore
            if (copySource != null && copySource.isSelectingForCopy())
                return false;

            if (e1 == null || e2 == null)
                return false;

            // if releasing then reset total scroll
            if (e2.getAction() == MotionEvent.ACTION_UP) {
                totalY = 0;
            }

            // activate consider if within x tolerance
            if (Math.abs(e1.getX() - e2.getX()) < ViewConfiguration.getTouchSlop() * 4) {

                View flip = findCurrentView(R.id.console_flip);
                if (flip == null)
                    return false;
                TerminalView terminal = (TerminalView) flip;

                // estimate how many rows we have scrolled through
                // accumulate distance that doesn't trigger immediate scroll
                totalY += distanceY;
                final int moved = (int) (totalY / terminal.bridge.charHeight);

                // consume as scrollback only if towards right half of screen
                if (e2.getX() > flip.getWidth() / 2) {
                    if (moved != 0) {
                        int base = terminal.bridge.buffer.getWindowBase();
                        terminal.bridge.buffer.setWindowBase(base + moved);
                        totalY = 0;
                        return true;
                    }
                } else {
                    // otherwise consume as pgup/pgdown for every 5 lines
                    if (moved > 5) {
                        ((vt320) terminal.bridge.buffer).keyPressed(vt320.KEY_PAGE_DOWN, ' ', 0);
                        terminal.bridge.tryKeyVibrate();
                        totalY = 0;
                        return true;
                    } else if (moved < -5) {
                        ((vt320) terminal.bridge.buffer).keyPressed(vt320.KEY_PAGE_UP, ' ', 0);
                        terminal.bridge.tryKeyVibrate();
                        totalY = 0;
                        return true;
                    }

                }

            }

            return false;
        }

    });

    flip.setLongClickable(true);
    flip.setOnTouchListener(new OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {

            // when copying, highlight the area
            if (copySource != null && copySource.isSelectingForCopy()) {
                int row = (int) Math.floor(event.getY() / copySource.charHeight);
                int col = (int) Math.floor(event.getX() / copySource.charWidth);

                SelectionArea area = copySource.getSelectionArea();

                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // recording starting area
                    if (area.isSelectingOrigin()) {
                        area.setRow(row);
                        area.setColumn(col);
                        lastTouchRow = row;
                        lastTouchCol = col;
                        copySource.redraw();
                    }
                    return true;
                case MotionEvent.ACTION_MOVE:
                    /* ignore when user hasn't moved since last time so
                     * we can fine-tune with directional pad
                     */
                    if (row == lastTouchRow && col == lastTouchCol)
                        return true;

                    // if the user moves, start the selection for other corner
                    area.finishSelectingOrigin();

                    // update selected area
                    area.setRow(row);
                    area.setColumn(col);
                    lastTouchRow = row;
                    lastTouchCol = col;
                    copySource.redraw();
                    return true;
                case MotionEvent.ACTION_UP:
                    /* If they didn't move their finger, maybe they meant to
                     * select the rest of the text with the directional pad.
                     */
                    if (area.getLeft() == area.getRight() && area.getTop() == area.getBottom()) {
                        return true;
                    }

                    // copy selected area to clipboard
                    String copiedText = area.copyFrom(copySource.buffer);

                    clipboard.setText(copiedText);
                    Toast.makeText(getActivity(), getString(R.string.console_copy_done, copiedText.length()),
                            Toast.LENGTH_LONG).show();
                    // fall through to clear state

                case MotionEvent.ACTION_CANCEL:
                    // make sure we clear any highlighted area
                    area.reset();
                    copySource.setSelectingForCopy(false);
                    copySource.redraw();
                    return true;
                }
            }

            Configuration config = getResources().getConfiguration();

            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                lastX = event.getX();
                lastY = event.getY();
            } else if (event.getAction() == MotionEvent.ACTION_UP && keyboardGroup.getVisibility() == View.GONE
                    && event.getEventTime() - event.getDownTime() < CLICK_TIME
                    && Math.abs(event.getX() - lastX) < MAX_CLICK_DISTANCE
                    && Math.abs(event.getY() - lastY) < MAX_CLICK_DISTANCE) {
                keyboardGroup.startAnimation(keyboard_fade_in);
                keyboardGroup.setVisibility(View.VISIBLE);

                mUIHandler.postDelayed(new Runnable() {
                    public void run() {
                        if (keyboardGroup.getVisibility() == View.GONE)
                            return;

                        keyboardGroup.startAnimation(keyboard_fade_out);
                        keyboardGroup.setVisibility(View.GONE);
                    }
                }, KEYBOARD_DISPLAY_TIME);
            }

            // pass any touch events back to detector
            return detect.onTouchEvent(event);
        }

    });

    return v;
}

From source file:com.ichi2.anki2.StudyOptionsFragment.java

protected View createView(LayoutInflater inflater, Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Log.i(AnkiDroidApp.TAG, "StudyOptions - createView()");

    restorePreferences();//from   w w w . j  a  v a 2  s .c  o  m

    mFragmented = getActivity().getClass() != StudyOptionsActivity.class;

    if (!AnkiDroidApp.colIsOpen()) {
        reloadCollection();
        return null;
    }

    //        Intent intent = getActivity().getIntent();
    //        if (intent != null && intent.hasExtra(DeckPicker.EXTRA_DECK_ID)) {
    //            mCol.getDecks().select(intent.getLongExtra(DeckPicker.EXTRA_DECK_ID, 1));
    //        }

    initAllContentViews(inflater);

    if (mSwipeEnabled) {
        gestureDetector = new GestureDetector(new MyGestureDetector());
        gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        };
    }

    if (getArguments().getBoolean("onlyFnsMsg")) {
        prepareCongratsView();
        mButtonCongratsFinish.setVisibility(View.GONE);
        return mCongratsView;
    } else {
        // clear undo if new deck is opened (do not clear if only congrats msg is shown)
        AnkiDroidApp.getCol().clearUndo();
    }

    mCramInitialConfig = getArguments().getBundle("cramInitialConfig");

    resetAndUpdateValuesFromDeck();

    return mStudyOptionsView;
}

From source file:com.hichinaschool.flashcards.anki.StudyOptionsFragment.java

protected View createView(LayoutInflater inflater, Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Log.i(AnkiDroidApp.TAG, "StudyOptions - createView()");

    restorePreferences();//from  www.  j  a  va 2  s .c  o  m

    mFragmented = getActivity().getClass() != StudyOptionsActivity.class;

    if (!AnkiDroidApp.colIsOpen()) {
        reloadCollection();
        return null;
    }

    //        Intent intent = getActivity().getIntent();
    //        if (intent != null && intent.hasExtra(DeckPicker.EXTRA_DECK_ID)) {
    //            mCol.getDecks().select(intent.getLongExtra(DeckPicker.EXTRA_DECK_ID, 1));
    //        }

    initAllContentViews(inflater);

    if (mSwipeEnabled) {
        gestureDetector = new GestureDetector(new MyGestureDetector());
        gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        };
    }

    if (getArguments().getBoolean("onlyFnsMsg")) {
        prepareCongratsView();
        return mCongratsView;
    } else {
        // clear undo if new deck is opened (do not clear if only congrats msg is shown)
        AnkiDroidApp.getCol().clearUndo();
    }

    mCramInitialConfig = getArguments().getBundle("cramInitialConfig");

    resetAndUpdateValuesFromDeck();

    return mStudyOptionsView;
}

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

@Override
@TargetApi(11)//from ww w.jav  a  2s .  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: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 av a  2  s  .co 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:com.xunlei.shortvideo.activity.VideoPublishLocal3Activity.java

private void initQupaiEditor() {
    //?????/*from  w ww .  j  a v  a 2s. co  m*/
    mSessionClient = new VideoSessionClientFactoryImpl().createSessionClient(this, null);
    WorkspaceClient workspace = mSessionClient.createWorkspace(this);
    mProjectConnection = new ProjectConnection(workspace);
    mActionParser = new EditorAction(mActionExecutor);
    mDataProvider = mSessionClient.getAssetRepository();
    mVideoSessionCreateInfo = mSessionClient.getCreateInfo();
    //??
    SceneFactoryClient sceneFactoryClient = new SceneFactoryClientImpl(this, mDataProvider,
            mSessionClient.getJSONSupport());

    //??
    SoundProjectFactoryClient soundFactoryClient = new SoundProjectFactoryClient(mDataProvider);

    mStageHost = new StageHost.Builder().addBitmapResolver(new BitmapLoader(this))
            //              .addBitmapResolver(new BitmapGenerator(sceneFactoryClient))
            .get();

    //        //intent?project,??savejson,?jsonproject
    String projectFilePath = mProjectUri.getPath();
    File projectFile = new File(projectFilePath);

    //?project.json???project
    mProject = ProjectUtil.readProject(projectFile, mSessionClient.getJSONSupport());
    if (mProject != null) {
        mProject.setProjectDir(projectFile.getParentFile(), projectFile);
        mProjectConnection.setProject(mProject);
    }

    //??.?1:1????.
    //        if(mProject.getRotation() == 90 || mProject.getRotation() == 270){
    //                mProject.setCanvasSize(mSessionClient.getProjectOptions().videoHeight, mSessionClient.getProjectOptions().videoWidth);
    //        }else {
    //                mProject.setCanvasSize(mSessionClient.getProjectOptions().videoWidth, mSessionClient.getProjectOptions().videoHeight);
    //        }

    mClient = new ProjectClient(mProjectConnection, mDataProvider, sceneFactoryClient, soundFactoryClient,
            mSessionClient.getJSONSupport());
    mClient.setDurationLimit(mProject.getDurationNano());
    mClient.setVideoFramerate(mSessionClient.getProjectOptions().videoFrameRate);
    mClientDelegate = new ProjectClientDelegate(mClient);
    mRepoClient = new AssetRepositoryClient(mDataProvider);

    //
    mPlayer = new ProjectPlayerControl(mStageHost);
    mPlayer.setOnProgressCallback(this);
    //        setContentView(R.layout.activity_editor);

    mClient.setOnChangeListener(mClientDelegate);

    //?
    mRenderConf = new RenderConfImpl(mProject, sceneFactoryClient, soundFactoryClient,
            mSessionClient.getJSONSupport());

    //
    mRenderConf.setVideoFrameRate(mSessionClient.getProjectOptions().videoFrameRate);

    //
    mRenderConf.setDurationLimit(TimeUnit.NANOSECONDS.toMillis(mProject.getDurationNano()));

    mEditorSession = new EditorSession(this, mPlayer, mDataProvider, mRenderConf,
            mSessionClient.getPageNavigator(), mClient);

    mStage = new Stage(mStageHost);
    mStage.realize();

    mDisplaySurface = (SurfaceView) findViewById(R.id.surface_view);

    //?
    int screenWidth = getResources().getDisplayMetrics().widthPixels;
    int screenHeight = getResources().getDisplayMetrics().heightPixels;
    FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mDisplaySurface.getLayoutParams();
    VideoScaleHelper helper = new VideoScaleHelper();
    helper.setVideoWidthAndHeight(mClient.getVideoWidth(), mClient.getVideoHeight())
            .setScreenWidthAndHeight(screenWidth, screenHeight).generateDisplayLayoutParams(lp);

    SurfaceHolder holder = mDisplaySurface.getHolder();
    mPlayer.getImpl().setSurface(holder);

    //        AspectRatioLayout video_frame = (AspectRatioLayout) findViewById(R.id.video);
    //        video_frame.setOriginalSize(480, 480);

    //        ViewStack view_stack = new ViewStack(View.INVISIBLE);
    //        view_stack.addView(findViewById(R.id.effect_list_filter));

    //        RecyclerView filter_list_view = (RecyclerView) findViewById(R.id.effect_list_filter);
    mMVlist = (RecyclerView) findViewById(R.id.effect_list_mv);

    //
    mFilterChooserMediator = new QupaiFilterChooseMediator(mClient, mDataProvider);
    mClientDelegate.addOnChangeListener(mFilterChooserMediator);

    mMVChooserMediator = new MVChooserMediator2(mMVlist, mEditorSession, mClientDelegate, mRepoClient);
    mMVChooserMediator.setMVItemClickListener(new MVChooserMediator2.OnMVItemClickListener() {
        @Override
        public void onItemClick(RecyclerView.Adapter adapter, View view, int position) {
            //reset filter
            mFilterIndex = 0;
            mFilterChooserMediator.setChecked(mFilterIndex);

            mConfig.setUseFilter(false);
            mConfig.setUseMV(position != 0);
        }
    });

    // ?MV
    new LoadDownloadMVTask().execute();

    //?,?

    mEditorSession.setPart(UIEditorPage.FILTER_EFFECT, mFilterChooserMediator);
    mEditorSession.setPart(UIEditorPage.MV, mMVChooserMediator);

    mEditorSession.updatePlayer(Integer.MAX_VALUE);
    mPlayer.start();
    mRenderTaskManager = new RenderTaskManager(getApplicationContext());
    mRenderTaskManager.setOnRenderTaskListener(this);
    mFilterIndex = 0;
    final int total = mFilterChooserMediator.getCount();
    final GestureDetector detector = new GestureDetector(new GestureDetector.OnGestureListener() {
        @Override
        public boolean onDown(MotionEvent e) {
            mFilterChanged = false;
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            hideMV();
            mFilterChanged = false;
            return true;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            float x = Math.abs(distanceX);
            if (x >= FILTER_TRIGGER_DISTANCE && !isMVMode()) {
                float y = Math.abs(distanceY);
                if ((y / x) < FILTER_TRIGGER_BIAS && !mFilterChanged) { //0.577 is 30 degree
                    if (distanceX < 0) {
                        statistic_click_filter();
                        mFilterChanged = true;
                        mFilterIndex++;
                        if (mFilterIndex >= total) {
                            mFilterIndex = 0;
                        }
                        //                            Log.d(TAG, "event.getx is " + event.getX() + " DownX is " + mDownX + " mFilterChanged is " + mFilterChanged);
                        mMVChooserMediator.resetPosition(0);
                        mEditorSession.setActiveEditorPage(UIEditorPage.FILTER_EFFECT);
                        mFilterChooserMediator.setChecked(mFilterIndex);
                        mFilterNameTv.setText(mFilterChooserMediator.getItemTitle(mFilterIndex));
                        mFilterNameTv.setAlpha(1);
                        mFilterNameTv.animate().alpha(0).setDuration(2000).start();
                    } else {
                        statistic_click_filter();
                        mFilterChanged = true;
                        mFilterIndex--;
                        if (mFilterIndex < 0) {
                            mFilterIndex = total - 1;
                        }
                        //                            Log.d(TAG, "event.getx is " + event.getX() + " DownX is " + mDownX + " mFilterChanged is " + mFilterChanged);
                        mMVChooserMediator.resetPosition(0);
                        mEditorSession.setActiveEditorPage(UIEditorPage.FILTER_EFFECT);
                        mFilterChooserMediator.setChecked(mFilterIndex);
                        mFilterNameTv.setText(mFilterChooserMediator.getItemTitle(mFilterIndex));
                        mFilterNameTv.setAlpha(1);
                        mFilterNameTv.animate().alpha(0).setDuration(2000).start();
                    }

                    mConfig.setUseFilter(mFilterIndex != 0);
                    mConfig.setUseMV(false);

                    return true;
                }
            }
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {

        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return false;
        }
    });
    mFilterOpLayer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            detector.onTouchEvent(event);
            return true;
        }
    });

    //        mFilterOpLayer.setOnTouchListener(new View.OnTouchListener() {
    //
    //            @Override
    //            public boolean onTouch(View v, MotionEvent event) {
    //                switch (event.getAction()) {
    //                    case MotionEvent.ACTION_DOWN:
    //                        hideMV();
    //                        mDownX = event.getX();
    //                        mFilterChanged = false;
    ////                        Log.d(TAG, "DownX is " + mDownX + " mFilterChanged is " + mFilterChanged);
    //                        return true;
    //                    case MotionEvent.ACTION_MOVE:
    //                        if((event.getX() - mDownX > 50) && !mFilterChanged) {
    //                            statistic_click_filter();
    //                            mFilterChanged = true;
    //                            mFilterIndex ++;
    //                            if(mFilterIndex >= total) {
    //                                mFilterIndex = 0;
    //                            }
    ////                            Log.d(TAG, "event.getx is " + event.getX() + " DownX is " + mDownX + " mFilterChanged is " + mFilterChanged);
    //                            mEditorSession.setActiveEditorPage(UIEditorPage.FILTER_EFFECT);
    //                            mFilterChooserMediator.resetPosition(mFilterIndex);
    //                            mFilterNameTv.setText(mFilterChooserMediator.getItemTitle(mFilterIndex));
    //                            mFilterNameTv.setAlpha(1);
    //                            mFilterNameTv.animate().alpha(0).setDuration(2000).start();
    //                            //select next
    //                            return true;
    //                        } else if((mDownX - event.getX() > 50) && !mFilterChanged) {
    //                            //select pre
    //                            statistic_click_filter();
    //                            mFilterChanged = true;
    //                            mFilterIndex --;
    //                            if(mFilterIndex < 0) {
    //                                mFilterIndex = total -1;
    //                            }
    ////                            Log.d(TAG, "event.getx is " + event.getX() + " DownX is " + mDownX + " mFilterChanged is " + mFilterChanged);
    //                            mEditorSession.setActiveEditorPage(UIEditorPage.FILTER_EFFECT);
    //                            mFilterChooserMediator.resetPosition(mFilterIndex);
    //                            mFilterNameTv.setText(mFilterChooserMediator.getItemTitle(mFilterIndex));
    //                            mFilterNameTv.setAlpha(1);
    //                            mFilterNameTv.animate().alpha(0).setDuration(2000).start();
    //                            return true;
    //                        }
    //                        break;
    //                    case MotionEvent.ACTION_UP:
    //                        mFilterChanged = false;
    //                        return false;
    //                }
    //                return false;
    //            }
    //        });

    mBtnChooseMv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mMvChooseContainer.getVisibility() != View.VISIBLE) {
                mBottomOpBar.setVisibility(View.GONE);
                mMvChooseContainer.setVisibility(View.VISIBLE);
                statistic_click_mv();
            } else {
                mBottomOpBar.setVisibility(View.VISIBLE);
                mMvChooseContainer.setVisibility(View.GONE);
            }
        }
    });
    mMvChooseContainer.setVisibility(View.GONE);
    initDir();
}

From source file:com.if3games.chessonline.DroidFish.java

private final void initUI() {
    leftHanded = leftHandedView();//from  w w w  . j  av a2s.  c  o  m
    if (!isSinglePlayer) {
        setContentView(leftHanded ? R.layout.main_left_handed_gms : R.layout.main_gms);
        for (int id : CLICKABLES) {
            findViewById(id).setOnClickListener(this);
        }
    } else {
        setContentView(leftHanded ? R.layout.main_left_handed : R.layout.main);
    }
    Util.overrideFonts(findViewById(android.R.id.content));

    // title lines need to be regenerated every time due to layout changes (rotations)
    secondTitleLine = findViewById(R.id.second_title_line);
    whiteTitleText = (TextView) findViewById(R.id.white_clock);
    whiteTitleText.setSelected(true);
    blackTitleText = (TextView) findViewById(R.id.black_clock);
    blackTitleText.setSelected(true);
    engineTitleText = (TextView) findViewById(R.id.title_text);
    whiteFigText = (TextView) findViewById(R.id.white_pieces);
    whiteFigText.setTypeface(figNotation);
    whiteFigText.setSelected(true);
    whiteFigText.setTextColor(whiteTitleText.getTextColors());
    blackFigText = (TextView) findViewById(R.id.black_pieces);
    blackFigText.setTypeface(figNotation);
    blackFigText.setSelected(true);
    blackFigText.setTextColor(blackTitleText.getTextColors());
    summaryTitleText = (TextView) findViewById(R.id.title_text_summary);

    player1TitleText = (TextView) findViewById(R.id.player1);
    player2TitleText = (TextView) findViewById(R.id.player2);

    status = (TextView) findViewById(R.id.status);
    moveListScroll = (ScrollView) findViewById(R.id.scrollView);
    moveList = (TextView) findViewById(R.id.moveList);
    defaultMoveListTypeFace = moveList.getTypeface();
    thinking = (TextView) findViewById(R.id.thinking);
    defaultThinkingListTypeFace = thinking.getTypeface();
    status.setFocusable(false);
    moveListScroll.setFocusable(false);
    moveList.setFocusable(false);
    moveList.setMovementMethod(LinkMovementMethod.getInstance());
    thinking.setFocusable(false);

    cb = (ChessBoardPlay) findViewById(R.id.chessboard);
    cb.setFocusable(true);
    cb.requestFocus();
    cb.setClickable(true);
    cb.setPgnOptions(pgnOptions);

    final GestureDetector gd = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
        private float scrollX = 0;
        private float scrollY = 0;

        @Override
        public boolean onDown(MotionEvent e) {
            if (!boardGestures) {
                handleClick(e);
                return true;
            }
            scrollX = 0;
            scrollY = 0;
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            if (!boardGestures)
                return false;
            cb.cancelLongPress();
            if (invertScrollDirection) {
                distanceX = -distanceX;
                distanceY = -distanceY;
            }
            if ((scrollSensitivity > 0) && (cb.sqSize > 0)) {
                scrollX += distanceX;
                scrollY += distanceY;
                float scrollUnit = cb.sqSize * scrollSensitivity;
                if (Math.abs(scrollX) >= Math.abs(scrollY)) {
                    // Undo/redo
                    int nRedo = 0, nUndo = 0;
                    while (scrollX > scrollUnit) {
                        nRedo++;
                        scrollX -= scrollUnit;
                    }
                    while (scrollX < -scrollUnit) {
                        nUndo++;
                        scrollX += scrollUnit;
                    }
                    if (nUndo + nRedo > 0)
                        scrollY = 0;
                    if (nRedo + nUndo > 1) {
                        boolean analysis = gameMode.analysisMode();
                        boolean human = gameMode.playerWhite() || gameMode.playerBlack();
                        if (analysis || !human)
                            ctrl.setGameMode(new GameMode(GameMode.TWO_PLAYERS));
                    }
                    for (int i = 0; i < nRedo; i++)
                        ctrl.redoMove();
                    for (int i = 0; i < nUndo; i++)
                        ctrl.undoMove();
                    ctrl.setGameMode(gameMode);
                } else {
                    // Next/previous variation
                    int varDelta = 0;
                    while (scrollY > scrollUnit) {
                        varDelta++;
                        scrollY -= scrollUnit;
                    }
                    while (scrollY < -scrollUnit) {
                        varDelta--;
                        scrollY += scrollUnit;
                    }
                    if (varDelta != 0)
                        scrollX = 0;
                    ctrl.changeVariation(varDelta);
                }
            }
            return true;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            if (!boardGestures)
                return false;
            cb.cancelLongPress();
            handleClick(e);
            return true;
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            if (!boardGestures)
                return false;
            if (e.getAction() == MotionEvent.ACTION_UP)
                handleClick(e);
            return true;
        }

        private final void handleClick(MotionEvent e) {
            if (ctrl.humansTurn() && myTurn) {
                int sq = cb.eventToSquare(e);
                Move m = cb.mousePressed(sq);
                if (m != null) {
                    ctrl.makeHumanMove(m);
                    if (!isSinglePlayer) {
                        if (!invalidMove)
                            broadcastMove(m.to, m.from);
                        else
                            invalidMove = false;
                    }
                }
                setEgtbHints(cb.getSelectedSquare());
            }
        }

        @Override
        public void onLongPress(MotionEvent e) {
            if (!boardGestures)
                return;
            ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(20);
            removeDialog(BOARD_MENU_DIALOG);
            showDialog(BOARD_MENU_DIALOG);
        }
    });
    cb.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            return gd.onTouchEvent(event);
        }
    });
    cb.setOnTrackballListener(new ChessBoard.OnTrackballListener() {
        public void onTrackballEvent(MotionEvent event) {
            if (ctrl.humansTurn()) {
                Move m = cb.handleTrackballEvent(event);
                if (m != null)
                    ctrl.makeHumanMove(m);
                setEgtbHints(cb.getSelectedSquare());
            }
        }
    });

    moveList.setOnLongClickListener(new OnLongClickListener() {
        public boolean onLongClick(View v) {
            removeDialog(MOVELIST_MENU_DIALOG);
            showDialog(MOVELIST_MENU_DIALOG);
            return true;
        }
    });
    thinking.setOnLongClickListener(new OnLongClickListener() {
        public boolean onLongClick(View v) {
            if (mShowThinking || gameMode.analysisMode()) {
                if (!pvMoves.isEmpty()) {
                    removeDialog(THINKING_MENU_DIALOG);
                    showDialog(THINKING_MENU_DIALOG);
                }
            }
            return true;
        }
    });

    custom1Button = (ImageButton) findViewById(R.id.custom1Button);
    custom1ButtonActions.setImageButton(custom1Button, this);
    custom2Button = (ImageButton) findViewById(R.id.custom2Button);
    custom2ButtonActions.setImageButton(custom2Button, this);
    custom3Button = (ImageButton) findViewById(R.id.custom3Button);
    custom3ButtonActions.setImageButton(custom3Button, this);

    modeButton = (ImageButton) findViewById(R.id.modeButton);
    modeButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isSinglePlayer)
                showDialog(GAME_MODE_DIALOG);
            else
                showDialog(GAME_GMS_MODE_DIALOG);
        }
    });
    undoButton = (ImageButton) findViewById(R.id.undoButton);
    redoButton = (ImageButton) findViewById(R.id.redoButton);

    if (isSinglePlayer) {
        undoButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ctrl.undoMove();
            }
        });
        undoButton.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                removeDialog(GO_BACK_MENU_DIALOG);
                showDialog(GO_BACK_MENU_DIALOG);
                return true;
            }
        });

        redoButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ctrl.redoMove();
            }
        });
        redoButton.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                removeDialog(GO_FORWARD_MENU_DIALOG);
                showDialog(GO_FORWARD_MENU_DIALOG);
                return true;
            }
        });
    } else {
        undoButton.setVisibility(View.GONE);
        redoButton.setVisibility(View.GONE);
    }
}