Example usage for android.view GestureDetector onTouchEvent

List of usage examples for android.view GestureDetector onTouchEvent

Introduction

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

Prototype

public boolean onTouchEvent(MotionEvent ev) 

Source Link

Document

Analyzes the given motion event and if applicable triggers the appropriate callbacks on the OnGestureListener supplied.

Usage

From source file:org.protocoderrunner.apprunner.api.PUI.java

@ProtocoderScript
@APIMethod(description = "Starts a gesture detector over a view", example = "")
@APIParam(params = { "View", "function(data)" })
//http://stackoverflow.com/questions/6599329/can-one-ongesturelistener-object-deal-with-two-gesturedetector-objects
public void gestureDetector(View v, final addGestureDetectorCB cb) {
    final GestureDetectorReturn g = new GestureDetectorReturn();

    final GestureDetector gestureDetector = new GestureDetector(a.get(),
            new GestureDetector.OnGestureListener() {

                @Override//from ww w  . ja  v  a2  s .co m
                public boolean onSingleTapUp(MotionEvent e) {

                    g.type = "up";
                    cb.event(g);
                    return false;
                }

                @Override
                public void onShowPress(MotionEvent e) {
                    g.type = "showpress";
                    cb.event(g);
                }

                @Override
                public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                    g.type = "scroll";
                    g.data = new JSONObject();
                    try {
                        g.data.put("distanceX", distanceX);
                        g.data.put("distanceY", distanceY);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    cb.event(g);
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    g.type = "longpress";
                    cb.event(g);
                }

                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                    g.type = "fling";
                    g.data = new JSONObject();
                    try {
                        g.data.put("velocityX", velocityX);
                        g.data.put("velocityY", velocityY);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    cb.event(g);
                    return true;
                }

                @Override
                public boolean onDown(MotionEvent e) {
                    g.type = "down";
                    cb.event(g);
                    return true;
                }
            });

    final ScaleGestureDetector scaleGestureDetector = new ScaleGestureDetector(a.get(),
            new OnScaleGestureListener() {
                @Override
                public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
                    g.type = "scale";
                    cb.event(g);
                    return false;
                }

                @Override
                public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) {
                    g.type = "scaleBegin";
                    cb.event(g);
                    return false;
                }

                @Override
                public void onScaleEnd(ScaleGestureDetector scaleGestureDetector) {
                    g.type = "scaleEnd";
                    cb.event(g);
                }
            });

    v.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            scaleGestureDetector.onTouchEvent(event);
            if (scaleGestureDetector.isInProgress())
                return true;
            gestureDetector.onTouchEvent(event);

            return true;
        }
    });
}

From source file:com.xunlei.shortvideo.activity.VideoPublishLocal3Activity.java

private void initQupaiEditor() {
    //?????//from  www .java 2 s .c o  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:org.appcelerator.titanium.view.TiUIView.java

protected void registerTouchEvents(final View touchable) {

    touchView = new WeakReference<View>(touchable);

    final ScaleGestureDetector scaleDetector = new ScaleGestureDetector(touchable.getContext(),
            new SimpleOnScaleGestureListener() {
                // protect from divide by zero errors
                long minTimeDelta = 1;
                float minStartSpan = 1.0f;
                float startSpan;

                @Override//from   ww w .  j ava2 s.  c o m
                public boolean onScale(ScaleGestureDetector sgd) {
                    if (proxy.hierarchyHasListener(TiC.EVENT_PINCH)) {
                        float timeDelta = sgd.getTimeDelta() == 0 ? minTimeDelta : sgd.getTimeDelta();

                        // Suppress scale events (and allow for possible two-finger tap events)
                        // until we've moved at least a few pixels. Without this check, two-finger 
                        // taps are very hard to register on some older devices.
                        if (!didScale) {
                            if (Math.abs(sgd.getCurrentSpan() - startSpan) > SCALE_THRESHOLD) {
                                didScale = true;
                            }
                        }

                        if (didScale) {
                            KrollDict data = new KrollDict();
                            data.put(TiC.EVENT_PROPERTY_SCALE, sgd.getCurrentSpan() / startSpan);
                            data.put(TiC.EVENT_PROPERTY_VELOCITY,
                                    (sgd.getScaleFactor() - 1.0f) / timeDelta * 1000);
                            data.put(TiC.EVENT_PROPERTY_SOURCE, proxy);

                            return proxy.fireEvent(TiC.EVENT_PINCH, data);
                        }
                    }
                    return false;
                }

                @Override
                public boolean onScaleBegin(ScaleGestureDetector sgd) {
                    startSpan = sgd.getCurrentSpan() == 0 ? minStartSpan : sgd.getCurrentSpan();
                    return true;
                }
            });

    final GestureDetector detector = new GestureDetector(touchable.getContext(), new SimpleOnGestureListener() {
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (proxy.hierarchyHasListener(TiC.EVENT_DOUBLE_TAP)
                    || proxy.hierarchyHasListener(TiC.EVENT_DOUBLE_CLICK)) {
                boolean handledTap = proxy.fireEvent(TiC.EVENT_DOUBLE_TAP, dictFromEvent(e));
                boolean handledClick = proxy.fireEvent(TiC.EVENT_DOUBLE_CLICK, dictFromEvent(e));
                return handledTap || handledClick;
            }
            return false;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            Log.d(TAG, "TAP, TAP, TAP on " + proxy, Log.DEBUG_MODE);
            if (proxy.hierarchyHasListener(TiC.EVENT_SINGLE_TAP)) {
                return proxy.fireEvent(TiC.EVENT_SINGLE_TAP, dictFromEvent(e));
                // Moved click handling to the onTouch listener, because a single tap is not the
                // same as a click. A single tap is a quick tap only, whereas clicks can be held
                // before lifting.
                // boolean handledClick = proxy.fireEvent(TiC.EVENT_CLICK, dictFromEvent(event));
                // Note: this return value is irrelevant in our case. We "want" to use it
                // in onTouch below, when we call detector.onTouchEvent(event); But, in fact,
                // onSingleTapConfirmed is *not* called in the course of onTouchEvent. It's
                // called via Handler in GestureDetector. <-- See its Java source.
                // return handledTap;// || handledClick;
            }
            return false;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            Log.d(TAG, "SWIPE on " + proxy, Log.DEBUG_MODE);
            if (proxy.hierarchyHasListener(TiC.EVENT_SWIPE)) {
                KrollDict data = dictFromEvent(e2);
                if (Math.abs(velocityX) > Math.abs(velocityY)) {
                    data.put(TiC.EVENT_PROPERTY_DIRECTION, velocityX > 0 ? "right" : "left");
                } else {
                    data.put(TiC.EVENT_PROPERTY_DIRECTION, velocityY > 0 ? "down" : "up");
                }
                return proxy.fireEvent(TiC.EVENT_SWIPE, data);
            }
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            Log.d(TAG, "LONGPRESS on " + proxy, Log.DEBUG_MODE);

            if (proxy.hierarchyHasListener(TiC.EVENT_LONGPRESS)) {
                proxy.fireEvent(TiC.EVENT_LONGPRESS, dictFromEvent(e));
            }
        }
    });

    touchable.setOnTouchListener(new OnTouchListener() {
        int pointersDown = 0;

        public boolean onTouch(View view, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                lastUpEvent.put(TiC.EVENT_PROPERTY_X, (double) event.getX());
                lastUpEvent.put(TiC.EVENT_PROPERTY_Y, (double) event.getY());
            }

            scaleDetector.onTouchEvent(event);
            if (scaleDetector.isInProgress()) {
                pointersDown = 0;
                return true;
            }

            boolean handled = detector.onTouchEvent(event);
            if (handled) {
                pointersDown = 0;
                return true;
            }

            if (event.getActionMasked() == MotionEvent.ACTION_POINTER_UP) {
                if (didScale) {
                    didScale = false;
                    pointersDown = 0;
                } else {
                    pointersDown++;
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                if (pointersDown == 1) {
                    proxy.fireEvent(TiC.EVENT_TWOFINGERTAP, dictFromEvent(event));
                    pointersDown = 0;
                    return true;
                }
                pointersDown = 0;
            }

            String motionEvent = motionEvents.get(event.getAction());
            if (motionEvent != null) {
                if (proxy.hierarchyHasListener(motionEvent)) {
                    proxy.fireEvent(motionEvent, dictFromEvent(event));
                }
            }

            // Inside View.java, dispatchTouchEvent() does not call onTouchEvent() if this listener returns true. As
            // a result, click and other motion events do not occur on the native Android side. To prevent this, we
            // always return false and let Android generate click and other motion events.
            return false;
        }
    });

}

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 2 s .c  o  m*/

            // 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:edu.mit.viral.shen.DroidFish.java

private final void initUI() {
    leftHanded = leftHandedView();/*from w w w .  j  a  v a2s  .  c  o m*/
    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);

    status = (TextView) findViewById(R.id.status);
    //   server = (TextView)findViewById(R.id.server);
    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()) {
                int sq = cb.eventToSquare(e);
                Move m = cb.mousePressed(sq);
                if (m != null) {
                    ctrl.makeHumanMove(m);
                    String longfen = TextIO.toFEN(cb.pos);
                    String sentout = utils.getSendMessageJSON(longfen);
                    sendJSON(sentout);
                    // String fen1=longfen.replaceAll("D","1");]
                    // commented out 04/12/15
                    // sendDataone(longfen, 1); 
                }

                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) {
        showDialog(GAME_MODE_DIALOG);
    }
            });
            */
    undoButton = (ImageButton) findViewById(R.id.undoButton);
    undoButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            ctrl.undoMove();
            sendDataone(TextIO.toFEN(cb.pos), 1);

        }
    });
    undoButton.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            removeDialog(GO_BACK_MENU_DIALOG);
            showDialog(GO_BACK_MENU_DIALOG);
            return true;
        }
    });

    commentButton = (ImageButton) findViewById(R.id.commentbutton);
    commentButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(DroidFish.this);
            builder.setTitle(R.string.edit_comments);
            View content = View.inflate(DroidFish.this, R.layout.edit_comments, null);
            builder.setView(content);

            DroidChessController.CommentInfo commInfo = ctrl.getComments();

            final TextView preComment, moveView, nag, postComment;
            preComment = (TextView) content.findViewById(R.id.ed_comments_pre);
            moveView = (TextView) content.findViewById(R.id.ed_comments_move);
            nag = (TextView) content.findViewById(R.id.ed_comments_nag);
            postComment = (TextView) content.findViewById(R.id.ed_comments_post);

            preComment.setText(commInfo.preComment);
            postComment.setText(commInfo.postComment);
            moveView.setText(commInfo.move);
            String nagStr = Node.nagStr(commInfo.nag).trim();
            if ((nagStr.length() == 0) && (commInfo.nag > 0))
                nagStr = String.format(Locale.US, "%d", commInfo.nag);
            nag.setText(nagStr);

            builder.setNegativeButton(R.string.cancel, null);
            builder.setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    String pre = preComment.getText().toString().trim();
                    String post = postComment.getText().toString().trim();
                    sendComment(post);
                    int nagVal = Node.strToNag(nag.getText().toString());

                    DroidChessController.CommentInfo commInfo = new DroidChessController.CommentInfo();
                    commInfo.preComment = pre;
                    commInfo.postComment = post;
                    commInfo.nag = nagVal;
                    ctrl.setComments(commInfo);

                }
            });

            builder.show();
        }
    });
    commentButton.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            removeDialog(GO_FORWARD_MENU_DIALOG);
            showDialog(GO_FORWARD_MENU_DIALOG);
            return true;
        }
    });

    redoButton = (ImageButton) findViewById(R.id.redoButton);
    redoButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            ctrl.redoMove();
            //startNewGame(2);
        }
    });
    redoButton.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            removeDialog(GO_FORWARD_MENU_DIALOG);
            showDialog(GO_FORWARD_MENU_DIALOG);
            return true;
        }
    });
}

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

private final void initUI() {
    leftHanded = leftHandedView();/*  w w  w  .  j a  v  a  2 s . 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);
    }
}