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

public GestureDetector(Context context, OnGestureListener listener) 

Source Link

Document

Creates a GestureDetector with the supplied listener.

Usage

From source file:com.farmerbb.notepad.fragment.NoteViewFragment.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override//from w ww .j ava2  s.  co m
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // Set values
    setRetainInstance(true);
    setHasOptionsMenu(true);

    // Get filename of saved note
    filename = getArguments().getString("filename");

    // Change window title
    String title;

    try {
        title = listener.loadNoteTitle(filename);
    } catch (IOException e) {
        title = getResources().getString(R.string.view_note);
    }

    getActivity().setTitle(title);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Bitmap bitmap = ((BitmapDrawable) ContextCompat.getDrawable(getActivity(), R.drawable.ic_recents_logo))
                .getBitmap();

        ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(title, bitmap,
                ContextCompat.getColor(getActivity(), R.color.primary));
        getActivity().setTaskDescription(taskDescription);
    }

    // Show the Up button in the action bar.
    ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Animate elevation change
    if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-large")
            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        LinearLayout noteViewEdit = getActivity().findViewById(R.id.noteViewEdit);
        LinearLayout noteList = getActivity().findViewById(R.id.noteList);

        noteList.animate().z(0f);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
            noteViewEdit.animate()
                    .z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation_land));
        else
            noteViewEdit.animate().z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation));
    }

    // Set up content view
    TextView noteContents = getActivity().findViewById(R.id.textView);
    markdownView = getActivity().findViewById(R.id.markdownView);

    // Apply theme
    SharedPreferences pref = getActivity().getSharedPreferences(getActivity().getPackageName() + "_preferences",
            Context.MODE_PRIVATE);
    ScrollView scrollView = getActivity().findViewById(R.id.scrollView);
    String theme = pref.getString("theme", "light-sans");
    int textSize = -1;
    int textColor = -1;

    String fontFamily = null;

    if (theme.contains("light")) {
        if (noteContents != null) {
            noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary));
            noteContents.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
        }

        if (markdownView != null) {
            markdownView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
            textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary);
        }

        scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
    }

    if (theme.contains("dark")) {
        if (noteContents != null) {
            noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark));
            noteContents
                    .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
        }

        if (markdownView != null) {
            markdownView
                    .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
            textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark);
        }

        scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
    }

    if (theme.contains("sans")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.SANS_SERIF);

        if (markdownView != null)
            fontFamily = "sans-serif";
    }

    if (theme.contains("serif")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.SERIF);

        if (markdownView != null)
            fontFamily = "serif";
    }

    if (theme.contains("monospace")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.MONOSPACE);

        if (markdownView != null)
            fontFamily = "monospace";
    }

    switch (pref.getString("font_size", "normal")) {
    case "smallest":
        textSize = 12;
        break;
    case "small":
        textSize = 14;
        break;
    case "normal":
        textSize = 16;
        break;
    case "large":
        textSize = 18;
        break;
    case "largest":
        textSize = 20;
        break;
    }

    if (noteContents != null)
        noteContents.setTextSize(textSize);

    String css = "";
    if (markdownView != null) {
        String topBottom = " " + Float.toString(getResources().getDimension(R.dimen.padding_top_bottom)
                / getResources().getDisplayMetrics().density) + "px";
        String leftRight = " " + Float.toString(getResources().getDimension(R.dimen.padding_left_right)
                / getResources().getDisplayMetrics().density) + "px";
        String fontSize = " " + Integer.toString(textSize) + "px";
        String fontColor = " #" + StringUtils.remove(Integer.toHexString(textColor), "ff");
        String linkColor = " #" + StringUtils.remove(
                Integer.toHexString(new TextView(getActivity()).getLinkTextColors().getDefaultColor()), "ff");

        css = "body { " + "margin:" + topBottom + topBottom + leftRight + leftRight + "; " + "font-family:"
                + fontFamily + "; " + "font-size:" + fontSize + "; " + "color:" + fontColor + "; " + "}"
                + "a { " + "color:" + linkColor + "; " + "}";

        markdownView.getSettings().setJavaScriptEnabled(false);
        markdownView.getSettings().setLoadsImagesAutomatically(false);
        markdownView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException | FileUriExposedException e) {
                        /* Gracefully fail */ }
                else
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        /* Gracefully fail */ }

                return true;
            }
        });
    }

    // Load note contents
    try {
        contentsOnLoad = listener.loadNote(filename);
    } catch (IOException e) {
        showToast(R.string.error_loading_note);

        // Add NoteListFragment or WelcomeFragment
        Fragment fragment;
        if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-normal"))
            fragment = new NoteListFragment();
        else
            fragment = new WelcomeFragment();

        getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteListFragment")
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
    }

    // Set TextView contents
    if (noteContents != null)
        noteContents.setText(contentsOnLoad);

    if (markdownView != null)
        markdownView.loadMarkdown(contentsOnLoad,
                "data:text/css;base64," + Base64.encodeToString(css.getBytes(), Base64.DEFAULT));

    // Show a toast message if this is the user's first time viewing a note
    final SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    firstLoad = sharedPref.getInt("first-load", 0);
    if (firstLoad == 0) {
        // Show dialog with info
        DialogFragment firstLoad = new FirstViewDialogFragment();
        firstLoad.show(getFragmentManager(), "firstloadfragment");

        // Set first-load preference to 1; we don't need to show the dialog anymore
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt("first-load", 1);
        editor.apply();
    }

    // Detect single and double-taps using GestureDetector
    final GestureDetector detector = new GestureDetector(getActivity(),
            new GestureDetector.OnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return false;
                }

                @Override
                public void onShowPress(MotionEvent e) {
                }

                @Override
                public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                    return false;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                }

                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                    return false;
                }

                @Override
                public boolean onDown(MotionEvent e) {
                    return false;
                }
            });

    detector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (sharedPref.getBoolean("show_double_tap_message", true)) {
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putBoolean("show_double_tap_message", false);
                editor.apply();
            }

            Bundle bundle = new Bundle();
            bundle.putString("filename", filename);

            Fragment fragment = new NoteEditFragment();
            fragment.setArguments(bundle);

            getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteEditFragment")
                    .commit();

            return false;
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if (sharedPref.getBoolean("show_double_tap_message", true) && showMessage) {
                showToastLong(R.string.double_tap);
                showMessage = false;
            }

            return false;
        }

    });

    if (noteContents != null)
        noteContents.setOnTouchListener((v, event) -> {
            detector.onTouchEvent(event);
            return false;
        });

    if (markdownView != null)
        markdownView.setOnTouchListener((v, event) -> {
            detector.onTouchEvent(event);
            return false;
        });
}

From source file:com.acbelter.scheduleview.ScheduleView.java

private void init(Context context) {
    if (!isInEditMode()) {
        mOverScroller = new OverScroller(context);
        mGestureListener = new GestureDetector.SimpleOnGestureListener() {
            @Override//w  w w . j av a 2 s . c om
            public boolean onDown(MotionEvent e) {
                if (DEBUG) {
                    Log.d(TAG, "onDown() y=" + mListY);
                }

                releaseEdgeEffects();
                mOverScroller.forceFinished(true);
                return true;
            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                if (DEBUG) {
                    Log.d(TAG, "onFling() y=" + mListY);
                }

                // Fling isn't needed
                if (mDeltaHeight < 0) {
                    return true;
                }

                mScrollDirection = velocityY > 0 ? 1 : -1;
                mOverScroller.fling(0, mListY, 0, (int) velocityY, 0, 0, -mDeltaHeight, 0);
                if (!awakenScrollBars()) {
                    ViewCompat.postInvalidateOnAnimation(ScheduleView.this);
                }
                return true;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                for (int i = 0; i < getChildCount(); i++) {
                    getChildAt(i).setPressed(false);
                }

                mListY -= (int) distanceY;
                recalculateOffset();

                positionItemViews();

                if (mListY == 0) {
                    mTopEdgeEffect.onPull(distanceY / (float) getHeight());
                    mTopEdgeEffectActive = true;
                }
                if (mListY == -mDeltaHeight) {
                    mBottomEdgeEffect.onPull(distanceY / (float) getHeight());
                    mBottomEdgeEffectActive = true;
                }

                if (!awakenScrollBars()) {
                    invalidate();
                }

                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                if (DEBUG) {
                    Log.d(TAG, "onLongPress() y=" + mListY);
                }

                View child;
                for (int i = 0; i < getChildCount(); i++) {
                    child = getChildAt(i);
                    child.getHitRect(mClickedViewBounds);
                    if (mClickedViewBounds.contains((int) e.getX(), (int) e.getY())) {
                        if (!mIsActionMode) {
                            mActionMode = startActionMode(mActionModeCallback);
                            mIsActionMode = true;
                        }

                        if (!child.isSelected()) {
                            mSelectedIds.add(mAdapter.getItemId(i));
                            child.setSelected(true);
                        } else {
                            mSelectedIds.remove(mAdapter.getItemId(i));
                            child.setSelected(false);
                        }

                        if (mSelectedIds.isEmpty()) {
                            finishActionMode();
                        }

                        invalidate();
                        return;
                    }
                }
            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                if (DEBUG) {
                    Log.d(TAG, "onSingleTapConfirmed() y=" + mListY);
                }

                View child;
                for (int i = 0; i < getChildCount(); i++) {
                    child = getChildAt(i);
                    child.getHitRect(mClickedViewBounds);
                    if (mClickedViewBounds.contains((int) e.getX(), (int) e.getY())) {
                        if (!mIsActionMode) {
                            OnItemClickListener callback = getOnItemClickListener();

                            if (callback != null) {
                                callback.onItemClick(ScheduleView.this, child, i, mAdapter.getItemId(i));
                            }
                        } else {
                            if (!child.isSelected()) {
                                mSelectedIds.add(mAdapter.getItemId(i));
                                child.setSelected(true);
                            } else {
                                mSelectedIds.remove(mAdapter.getItemId(i));
                                child.setSelected(false);
                            }

                            if (mSelectedIds.isEmpty()) {
                                finishActionMode();
                            }

                            invalidate();
                        }
                        break;
                    }
                }
                return true;
            }
        };

        mGestureDetector = new GestureDetector(context, mGestureListener);
    }
}

From source file:com.anjalimacwan.fragment.NoteViewFragment.java

@SuppressLint("SetJavaScriptEnabled")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override/*www .  j  av a2 s  .  com*/
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // Set values
    setRetainInstance(true);
    setHasOptionsMenu(true);

    // Get filename of saved note
    filename = getArguments().getString("filename");

    // Change window title
    String title;

    try {
        title = listener.loadNoteTitle(filename);
    } catch (IOException e) {
        title = getResources().getString(R.string.view_note);
    }

    getActivity().setTitle(title);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(title, null,
                ContextCompat.getColor(getActivity(), R.color.primary));
        getActivity().setTaskDescription(taskDescription);
    }

    // Show the Up button in the action bar.
    ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Animate elevation change
    if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-large")
            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        LinearLayout noteViewEdit = (LinearLayout) getActivity().findViewById(R.id.noteViewEdit);
        LinearLayout noteList = (LinearLayout) getActivity().findViewById(R.id.noteList);

        noteList.animate().z(0f);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
            noteViewEdit.animate()
                    .z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation_land));
        else
            noteViewEdit.animate().z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation));
    }

    // Set up content view
    TextView noteContents = (TextView) getActivity().findViewById(R.id.textView);
    markdownView = (MarkdownView) getActivity().findViewById(R.id.markdownView);

    // Apply theme
    SharedPreferences pref = getActivity().getSharedPreferences(getActivity().getPackageName() + "_preferences",
            Context.MODE_PRIVATE);
    ScrollView scrollView = (ScrollView) getActivity().findViewById(R.id.scrollView);
    String theme = pref.getString("theme", "light-sans");
    int textSize = -1;
    int textColor = -1;

    String fontFamily = null;

    if (theme.contains("light")) {
        if (noteContents != null) {
            noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary));
            noteContents.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
        }

        if (markdownView != null) {
            markdownView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
            textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary);
        }

        scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background));
    }

    if (theme.contains("dark")) {
        if (noteContents != null) {
            noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark));
            noteContents
                    .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
        }

        if (markdownView != null) {
            markdownView
                    .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
            textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark);
        }

        scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark));
    }

    if (theme.contains("sans")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.SANS_SERIF);

        if (markdownView != null)
            fontFamily = "sans-serif";
    }

    if (theme.contains("serif")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.SERIF);

        if (markdownView != null)
            fontFamily = "serif";
    }

    if (theme.contains("monospace")) {
        if (noteContents != null)
            noteContents.setTypeface(Typeface.MONOSPACE);

        if (markdownView != null)
            fontFamily = "monospace";
    }

    switch (pref.getString("font_size", "normal")) {
    case "smallest":
        textSize = 12;
        break;
    case "small":
        textSize = 14;
        break;
    case "normal":
        textSize = 16;
        break;
    case "large":
        textSize = 18;
        break;
    case "largest":
        textSize = 20;
        break;
    }

    if (noteContents != null)
        noteContents.setTextSize(textSize);

    if (markdownView != null) {
        String topBottom = " " + Float.toString(getResources().getDimension(R.dimen.padding_top_bottom)
                / getResources().getDisplayMetrics().density) + "px";
        String leftRight = " " + Float.toString(getResources().getDimension(R.dimen.padding_left_right)
                / getResources().getDisplayMetrics().density) + "px";
        String fontSize = " " + Integer.toString(textSize) + "px";
        String fontColor = " #" + StringUtils.remove(Integer.toHexString(textColor), "ff");

        final String css = "body { " + "margin:" + topBottom + topBottom + leftRight + leftRight + "; "
                + "font-family:" + fontFamily + "; " + "font-size:" + fontSize + "; " + "color:" + fontColor
                + "; " + "}";

        final String js = "var styleNode = document.createElement('style');\n"
                + "styleNode.type = \"text/css\";\n" + "var styleText = document.createTextNode('" + css
                + "');\n" + "styleNode.appendChild(styleText);\n"
                + "document.getElementsByTagName('head')[0].appendChild(styleNode);\n";

        markdownView.getSettings().setJavaScriptEnabled(true);
        markdownView.getSettings().setLoadsImagesAutomatically(false);
        markdownView.setWebViewClient(new WebViewClient() {
            @TargetApi(Build.VERSION_CODES.N)
            @Override
            public void onLoadResource(WebView view, String url) {
                view.stopLoading();
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException | FileUriExposedException e) {
                        /* Gracefully fail */ }
                else
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        /* Gracefully fail */ }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
                    view.evaluateJavascript(js, null);
                else
                    view.loadUrl("javascript:" + js);
            }
        });
    }

    // Load note contents
    try {
        contentsOnLoad = listener.loadNote(filename);
    } catch (IOException e) {
        showToast(R.string.error_loading_note);

        // Add NoteListFragment or WelcomeFragment
        Fragment fragment;
        if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-normal"))
            fragment = new NoteListFragment();
        else
            fragment = new WelcomeFragment();

        getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteListFragment")
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
    }

    // Set TextView contents
    if (noteContents != null)
        noteContents.setText(contentsOnLoad);

    if (markdownView != null)
        markdownView.loadMarkdown(contentsOnLoad);

    // Show a toast message if this is the user's first time viewing a note
    final SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    firstLoad = sharedPref.getInt("first-load", 0);
    if (firstLoad == 0) {
        // Show dialog with info
        DialogFragment firstLoad = new FirstViewDialogFragment();
        firstLoad.show(getFragmentManager(), "firstloadfragment");

        // Set first-load preference to 1; we don't need to show the dialog anymore
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt("first-load", 1);
        editor.apply();
    }

    // Detect single and double-taps using GestureDetector
    final GestureDetector detector = new GestureDetector(getActivity(),
            new GestureDetector.OnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return false;
                }

                @Override
                public void onShowPress(MotionEvent e) {
                }

                @Override
                public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                    return false;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                }

                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                    return false;
                }

                @Override
                public boolean onDown(MotionEvent e) {
                    return false;
                }
            });

    detector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (sharedPref.getBoolean("show_double_tap_message", true)) {
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putBoolean("show_double_tap_message", false);
                editor.apply();
            }

            Bundle bundle = new Bundle();
            bundle.putString("filename", filename);

            Fragment fragment = new NoteEditFragment();
            fragment.setArguments(bundle);

            getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteEditFragment")
                    .commit();

            return false;
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if (sharedPref.getBoolean("show_double_tap_message", true) && showMessage) {
                showToastLong(R.string.double_tap);
                showMessage = false;
            }

            return false;
        }

    });

    if (noteContents != null)
        noteContents.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                detector.onTouchEvent(event);
                return false;
            }
        });

    if (markdownView != null)
        markdownView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                detector.onTouchEvent(event);
                return false;
            }
        });
}

From source file:org.readium.sdk.android.biblemesh.WebViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);

    setContentView(R.layout.activity_web_view);

    final int abTitleId = getResources().getIdentifier("action_bar_title", "id", "android");
    findViewById(abTitleId).setOnClickListener(new View.OnClickListener() {

        @Override//w w w. jav a 2  s.co  m
        public void onClick(View v) {
            finish();
        }
    });

    mWebview = (WebView) findViewById(R.id.webview);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
            && 0 != (getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    mProgress = (ProgressBar) findViewById(R.id.progressBar);
    initWebView();

    final GestureDetector gestureDetector = new GestureDetector(this, new MyGestureListener());

    mWebview.setOnTouchListener(new View.OnTouchListener() {

        private final static long MAX_TOUCH_DURATION = 150;
        float lastEventX;
        float m_DownTime;

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastEventX = event.getX();
                m_DownTime = event.getEventTime(); //init time
                break;
            case MotionEvent.ACTION_MOVE: {
                float distanceX = lastEventX - event.getX();

                ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) mWebview
                        .getLayoutParams();

                marginLayoutParams.leftMargin = marginLayoutParams.leftMargin - (int) distanceX;
                marginLayoutParams.rightMargin = -marginLayoutParams.leftMargin;// marginLayoutParams.rightMargin + (int) distanceX;

                mWebview.requestLayout();
            }
                break;
            case MotionEvent.ACTION_UP: {
                ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) mWebview
                        .getLayoutParams();
                if (marginLayoutParams.leftMargin < 10 && marginLayoutParams.leftMargin > -10) {
                    Log.i("up", "small margin, open menu?");
                    if (event.getEventTime() - m_DownTime <= MAX_TOUCH_DURATION) {
                        Log.i("up", "quick");
                        showActionBar(null);
                    } else {
                        Log.i("up", "too long");
                    }
                }
            }
            case MotionEvent.ACTION_CANCEL: {
                ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) mWebview
                        .getLayoutParams();

                //Log.i("snap", "snap width: "+mWebview.getWidth()+" left:" + marginLayoutParams.leftMargin + " raw:" + event.getRawX() + " " + event.getX());//+" "+e2.toString()+" "+e1.toString());
                //mWebview.getWidth()
                if (marginLayoutParams.leftMargin < -0.5 * mWebview.getWidth()) {
                    mReadiumJSApi.openPageRight();
                    mWebview.setAlpha(0.0f);
                } else if (marginLayoutParams.leftMargin > 0.5 * mWebview.getWidth()) {
                    mReadiumJSApi.openPageLeft();
                    mWebview.setAlpha(0.0f);
                } else {
                    snapBack();
                    //return true;
                }
            }
                break;
            }
            ;
            return gestureDetector.onTouchEvent(event);
        }
    });
    /*mWebview.setHapticFeedbackEnabled(false);*/

    Intent intent = getIntent();
    if (intent.getFlags() == Intent.FLAG_ACTIVITY_NEW_TASK) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mContainer = ContainerHolder.getInstance().get(extras.getLong(Constants.CONTAINER_ID));
            if (mContainer == null) {
                finish();
                return;
            }
            mPackage = mContainer.getDefaultPackage();

            String rootUrl = "http://" + EpubServer.HTTP_HOST + ":" + EpubServer.HTTP_PORT + "/";
            mPackage.setRootUrls(rootUrl, null);

            try {
                mOpenPageRequestData = OpenPageRequest
                        .fromJSON(extras.getString(Constants.OPEN_PAGE_REQUEST_DATA));
            } catch (JSONException e) {
                Log.e(TAG, "Constants.OPEN_PAGE_REQUEST_DATA must be a valid JSON object: " + e.getMessage(),
                        e);
            }
        }
    }

    // No need, EpubServer already launchers its own thread
    // new AsyncTask<Void, Void, Void>() {
    // @Override
    // protected Void doInBackground(Void... params) {
    // //xxx
    // return null;
    // }
    // }.execute();

    mServer = new EpubServer(EpubServer.HTTP_HOST, EpubServer.HTTP_PORT, mPackage, quiet, dataPreProcessor);
    mServer.startServer();

    // Load the page skeleton
    mWebview.loadUrl(READER_SKELETON);
    mViewerSettings = new ViewerSettings(ViewerSettings.SyntheticSpreadMode.SINGLE,
            ViewerSettings.ScrollMode.AUTO, 100, 20);

    mReadiumJSApi = new ReadiumJSApi(new ReadiumJSApi.JSLoader() {
        @Override
        public void loadJS(String javascript) {
            mWebview.loadUrl(javascript);
        }
    });

    /*Button back = (Button)findViewById(R.id.btnBack);
    back.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
    onBackPressed();
    if(getActionBar.isShowing())
    {
       hideActionBar();
    }
    else
    {
       getActionBar.show();
       hideActionBar();
    }
       }
    });*/
    r = new Runnable() {
        @Override
        public void run() {
            getActionBar().hide();
            //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
        }
    };
    hide2 = null;
    hideActionBar();
    //ActionBar actionBar = getActionBar();
    //actionBar.hide();
    //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}

From source file:com.javielinux.tweettopics2.TweetTopicsActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    try {/*from ww  w  . ja  v a  2 s. c  o m*/
        DataFramework.getInstance().open(this, Utils.packageName);
    } catch (Exception e) {
        e.printStackTrace();
    }

    super.onCreate(savedInstanceState);

    CacheData.getInstance().fillHide();

    ConnectionManager.getInstance().open(this);
    ConnectionManager.getInstance().loadUsers();

    OnAlarmReceiver.callAlarm(this);

    if (PreferenceUtils.getFinishForceClose(this)) {
        PreferenceUtils.setFinishForceClose(this, false);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.title_crash);
        builder.setMessage(R.string.msg_crash);
        builder.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                Utils.sendLastCrash(TweetTopicsActivity.this);
            }
        });
        builder.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            }
        });
        builder.create();
        builder.show();
    }

    Thread.UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
    if (currentHandler != null) {
        Thread.setDefaultUncaughtExceptionHandler(new ErrorReporter(currentHandler, getApplication()));
    }

    if (PreferenceManager.getDefaultSharedPreferences(this).getString("prf_orientation", "2").equals("2")) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    }

    // borrar notificaciones
    if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("prf_notif_delete_notifications_inside",
            true)) {
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancelAll();
    }

    long goToColumnPosition = -1;
    int goToColumnType = -1;
    long goToColumnUser = -1;
    long goToColumnSearch = -1;
    long selectedTweetId = -1;

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        if (extras.containsKey(KEY_EXTRAS_GOTO_COLUMN_POSITION)) {
            goToColumnPosition = extras.getLong(KEY_EXTRAS_GOTO_COLUMN_POSITION);
        }
        if (extras.containsKey(KEY_EXTRAS_GOTO_COLUMN_TYPE)) {
            goToColumnType = extras.getInt(KEY_EXTRAS_GOTO_COLUMN_TYPE);
        }
        if (extras.containsKey(KEY_EXTRAS_GOTO_COLUMN_USER)) {
            goToColumnUser = extras.getLong(KEY_EXTRAS_GOTO_COLUMN_USER);
        }
        if (extras.containsKey(KEY_EXTRAS_GOTO_COLUMN_SEARCH)) {
            goToColumnSearch = extras.getLong(KEY_EXTRAS_GOTO_COLUMN_SEARCH);
        }
        if (extras.containsKey(KEY_EXTRAS_GOTO_TWEET_ID)) {
            selectedTweetId = extras.getLong(KEY_EXTRAS_GOTO_TWEET_ID);
        }
    }

    int positionFromSensor = -1;
    if (savedInstanceState != null && savedInstanceState.containsKey(KEY_SAVE_STATE_COLUMN_POS)) {
        positionFromSensor = savedInstanceState.getInt(KEY_SAVE_STATE_COLUMN_POS);
    }

    Utils.createDirectoriesIfIsNecessary();

    Display display = getWindowManager().getDefaultDisplay();
    widthScreen = display.getWidth();
    heightScreen = display.getHeight();

    themeManager = new ThemeManager(this);
    themeManager.setTheme();

    setContentView(R.layout.tweettopics_activity);

    fragmentAdapter = new TweetTopicsFragmentAdapter(this, getSupportFragmentManager());

    pager = (ViewPager) findViewById(R.id.tweet_pager);
    pager.setAdapter(fragmentAdapter);

    indicator = (TitlePageIndicator) findViewById(R.id.tweettopics_bar_indicator);
    indicator.setFooterIndicatorStyle(TitlePageIndicator.IndicatorStyle.Triangle);
    indicator.setFooterLineHeight(0);
    indicator.setFooterColor(Color.WHITE);
    indicator.setClipPadding(-getWindowManager().getDefaultDisplay().getWidth());
    indicator.setViewPager(pager);
    indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i1) {
        }

        @Override
        public void onPageSelected(int i) {
            reloadBarAvatar();
            if (i == 0) {
                refreshMyActivity();
            }
        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });
    indicator.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showActionBarColumns();
        }
    });

    findViewById(R.id.tweettopics_bar_my_activity).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showActionBarIndicatorAndMovePager(0);
        }
    });

    findViewById(R.id.tweettopics_bar_options).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showMenuColumnsOptions(view);
        }
    });

    layoutOptionsColumns = (LinearLayout) findViewById(R.id.tweettopics_ll_options_columns);
    layoutMainOptionsColumns = (LinearLayout) findViewById(R.id.tweettopics_ll_main_options_columns);
    layoutMainOptionsColumns.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            hideOptionsColumns();
        }
    });
    btnOptionsColumnsMain = (Button) findViewById(R.id.tweettopics_ll_options_columns_btn_main);
    btnOptionsColumnsMain.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int pos = Integer.valueOf(view.getTag().toString());
            Toast.makeText(TweetTopicsActivity.this,
                    getString(R.string.column_main_message, fragmentAdapter.setColumnActive(pos)),
                    Toast.LENGTH_LONG).show();
            hideOptionsColumns();
        }
    });
    btnOptionsColumnsEdit = (Button) findViewById(R.id.tweettopics_ll_options_columns_btn_edit);
    btnOptionsColumnsEdit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int pos = Integer.valueOf(view.getTag().toString());
            EditColumnDialogFragment frag = new EditColumnDialogFragment(
                    fragmentAdapter.getFragmentList().get(pos), new Callable() {
                        @Override
                        public Object call() throws Exception {
                            refreshActionBarColumns();
                            return null;
                        }
                    });
            frag.show(getSupportFragmentManager(), "dialog");
            hideOptionsColumns();
        }
    });

    // cargar el popup de enlaces

    FrameLayout root = ((FrameLayout) findViewById(R.id.tweettopics_root));
    popupLinks = new PopupLinks(this);
    popupLinks.loadPopup(root);

    splitActionBarMenu = new SplitActionBarMenu(this);
    splitActionBarMenu.loadSplitActionBarMenu(root);

    layoutBackgroundApp = (RelativeLayout) findViewById(R.id.tweettopics_layout_background_app);

    layoutBackgroundBar = (RelativeLayout) findViewById(R.id.tweettopics_bar_background);

    horizontalScrollViewColumns = (HorizontalScrollView) findViewById(R.id.tweettopics_bar_horizontal_scroll);

    layoutBackgroundColumnsBarContainer = (LinearLayout) findViewById(R.id.tweettopics_bar_columns_container);

    layoutBackgroundColumnsBar = (LinearLayout) findViewById(R.id.tweettopics_bar_columns);
    //        layoutBackgroundColumnsBar.setCols(4);
    //
    //        layoutBackgroundColumnsBar.setOnRearrangeListener(new OnRearrangeListener() {
    //            public void onRearrange(int oldIndex, int newIndex) {
    //                reorganizeColumns(oldIndex, newIndex);
    //            }
    //
    //            @Override
    //            public void onStartDrag(int x, int index) {
    //                showOptionsColumns(x, index, true);
    //            }
    //
    //            @Override
    //            public void onMoveDragged(int index) {
    //                hideOptionsColumns();
    //            }
    //
    //        });
    //        layoutBackgroundColumnsBar.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    //            @Override
    //            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
    //                showActionBarIndicatorAndMovePager(position);
    //            }
    //        });

    imgBarAvatar = (ImageView) findViewById(R.id.tweettopics_bar_avatar);
    imgBarAvatarBg = (ImageView) findViewById(R.id.tweettopics_bar_avatar_bg);
    imgBarCounter = (TextView) findViewById(R.id.tweettopics_bar_counter);
    imgNewStatus = (ImageView) findViewById(R.id.tweettopics_bar_new_status);
    imgNewStatus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            newStatus();
        }
    });

    imgBarAvatarGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public void onLongPress(MotionEvent e) {
            if (fragmentAdapter.instantiateItem(pager, pager.getCurrentItem()) instanceof BaseListFragment) {
                ((BaseListFragment) fragmentAdapter.instantiateItem(pager, pager.getCurrentItem())).goToTop();
            }
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (fragmentAdapter.instantiateItem(pager, pager.getCurrentItem()) instanceof BaseListFragment) {
                ((BaseListFragment) fragmentAdapter.instantiateItem(pager, pager.getCurrentItem())).goToTop();
            }
            return true;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            animateDragged();
            return true;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }
    });

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

    refreshTheme();

    reloadBarAvatar();

    refreshActionBarColumns();

    if (goToColumnType >= 0) {
        if ((goToColumnType == TweetTopicsUtils.COLUMN_TIMELINE
                || goToColumnType == TweetTopicsUtils.COLUMN_MENTIONS
                || goToColumnType == TweetTopicsUtils.COLUMN_DIRECT_MESSAGES) && goToColumnUser >= 0) {
            openUserColumn(goToColumnUser, goToColumnType);
        }
        if (goToColumnType == TweetTopicsUtils.COLUMN_SEARCH && goToColumnSearch > 0) {
            openSearchColumn(new Entity("search", goToColumnSearch));
        }
    } else if (goToColumnType == TweetTopicsUtils.COLUMN_MY_ACTIVITY) {
    } else if (goToColumnPosition > 0) {
        goToColumn((int) goToColumnPosition, false, selectedTweetId);
    } else if (positionFromSensor >= 0) {
        goToColumn(positionFromSensor, false, selectedTweetId);
    } else {
        int col = fragmentAdapter.getPositionColumnActive();
        if (col > 0)
            goToColumn(col, false, selectedTweetId);
    }

    // comprobar si hay que proponer ir al market

    int access_count = PreferenceUtils.getApplicationAccessCount(this);

    if (access_count <= 20) {
        if (access_count == 20) {
            try {
                AlertDialog dialog = DialogUtils.RateAppDialogBuilder.create(this);
                dialog.show();
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }

        PreferenceUtils.setApplicationAccessCount(this, access_count + 1);
    }

    PreferenceUtils.showChangeLog(this, true);

}

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

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

    DisplayMetrics metrics = new DisplayMetrics();
    SherlockFragmentActivity activity = getSherlockActivity();

    activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

    displayPageNumber(-1); // Initializes the pagenumber view properly

    final GestureDetector gestureDetector = new GestureDetector(context,
            new NavGestureDetector(bookView, this, metrics));

    View.OnTouchListener gestureListener = (View v, MotionEvent event) -> !ttsIsRunning()
            && gestureDetector.onTouchEvent(event);

    this.viewSwitcher.setOnTouchListener(gestureListener);
    this.bookView.setOnTouchListener(gestureListener);
    this.dummyView.setOnTouchListener(gestureListener);

    registerForContextMenu(bookView);//from   w  ww  . j  ava  2 s.co m
    saveConfigState();

    Intent intent = activity.getIntent();
    String file = null;

    if (intent.getData() != null) {
        file = intent.getData().getPath();
    }

    if (file == null) {
        file = config.getLastOpenedFile();
    }

    updateFromPrefs();
    updateFileName(savedInstanceState, file);

    if ("".equals(fileName) || !new File(fileName).exists()) {

        LOG.info("Requested to open file " + fileName + ", which doesn't seem to exist. "
                + "Switching back to the library.");

        Intent newIntent = new Intent(context, LibraryActivity.class);
        startActivity(newIntent);
        activity.finish();
        return;

    } else {

        if (savedInstanceState == null && config.isSyncEnabled()) {
            new DownloadProgressTask().execute();
        } else {
            bookView.restore();
        }
    }

    if (ttsIsRunning()) {
        this.mediaLayout.setVisibility(View.VISIBLE);
        this.ttsPlaybackItemQueue.updateSpeechCompletedCallbacks(this::speechCompleted);
        uiHandler.post(progressBarUpdater);
    }

    activity.getSupportActionBar().addOnMenuVisibilityListener(isVisible -> {

        LOG.debug("Detected change of visibility in action-bar: visible=" + isVisible);
        int visibility = isVisible ? View.VISIBLE : View.GONE;
        titleBarLayout.setVisibility(visibility);

    });

}

From source file:org.akop.crosswords.view.CrosswordView.java

public CrosswordView(Context context, AttributeSet attrs) {
    super(context, attrs);

    if (!isInEditMode()) {
        setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }/*  w w  w.ja  v  a  2  s  .  c o m*/

    // Set drawing defaults
    Resources r = context.getResources();
    DisplayMetrics dm = r.getDisplayMetrics();

    int cellFillColor = NORMAL_CELL_FILL_COLOR;
    int cheatedCellFillColor = CHEATED_CELL_FILL_COLOR;
    int mistakeCellFillColor = MISTAKE_CELL_FILL_COLOR;
    int selectedWordFillColor = SELECTED_WORD_FILL_COLOR;
    int selectedCellFillColor = SELECTED_CELL_FILL_COLOR;
    int textColor = TEXT_COLOR;
    int cellStrokeColor = CELL_STROKE_COLOR;
    int circleStrokeColor = CIRCLE_STROKE_COLOR;

    float numberTextSize = NUMBER_TEXT_SIZE * dm.scaledDensity;
    float answerTextSize = ANSWER_TEXT_SIZE * dm.scaledDensity;

    mCellSize = CELL_SIZE * dm.density;
    mNumberTextPadding = NUMBER_TEXT_PADDING * dm.density;
    mAnswerTextPadding = ANSWER_TEXT_PADDING * dm.density;

    // Read supplied attributes
    if (attrs != null) {
        Resources.Theme theme = context.getTheme();
        TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.Crossword, 0, 0);
        mCellSize = a.getDimension(R.styleable.Crossword_cellSize, mCellSize);
        mNumberTextPadding = a.getDimension(R.styleable.Crossword_numberTextPadding, mNumberTextPadding);
        numberTextSize = a.getDimension(R.styleable.Crossword_numberTextSize, numberTextSize);
        mAnswerTextPadding = a.getDimension(R.styleable.Crossword_answerTextPadding, mAnswerTextPadding);
        answerTextSize = a.getDimension(R.styleable.Crossword_answerTextSize, answerTextSize);
        cellFillColor = a.getColor(R.styleable.Crossword_defaultCellFillColor, cellFillColor);
        cheatedCellFillColor = a.getColor(R.styleable.Crossword_cheatedCellFillColor, cheatedCellFillColor);
        mistakeCellFillColor = a.getColor(R.styleable.Crossword_mistakeCellFillColor, mistakeCellFillColor);
        selectedWordFillColor = a.getColor(R.styleable.Crossword_selectedWordFillColor, selectedWordFillColor);
        selectedCellFillColor = a.getColor(R.styleable.Crossword_selectedCellFillColor, selectedCellFillColor);
        cellStrokeColor = a.getColor(R.styleable.Crossword_cellStrokeColor, cellStrokeColor);
        circleStrokeColor = a.getColor(R.styleable.Crossword_circleStrokeColor, circleStrokeColor);
        textColor = a.getColor(R.styleable.Crossword_textColor, textColor);
        a.recycle();
    }

    mMarkerSideLength = mCellSize * MARKER_TRIANGLE_LENGTH_FRACTION;

    // Init paints
    mCellFillPaint = new Paint();
    mCellFillPaint.setColor(cellFillColor);
    mCellFillPaint.setStyle(Paint.Style.FILL);

    mCheatedCellFillPaint = new Paint();
    mCheatedCellFillPaint.setColor(cheatedCellFillColor);
    mCheatedCellFillPaint.setStyle(Paint.Style.FILL);

    mMistakeCellFillPaint = new Paint();
    mMistakeCellFillPaint.setColor(mistakeCellFillColor);
    mMistakeCellFillPaint.setStyle(Paint.Style.FILL);

    mSelectedWordFillPaint = new Paint();
    mSelectedWordFillPaint.setColor(selectedWordFillColor);
    mSelectedWordFillPaint.setStyle(Paint.Style.FILL);

    mSelectedCellFillPaint = new Paint();
    mSelectedCellFillPaint.setColor(selectedCellFillColor);
    mSelectedCellFillPaint.setStyle(Paint.Style.FILL);

    mCellStrokePaint = new Paint();
    mCellStrokePaint.setColor(cellStrokeColor);
    mCellStrokePaint.setStyle(Paint.Style.STROKE);
    //      mCellStrokePaint.setStrokeWidth(1);

    mCircleStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mCircleStrokePaint.setColor(circleStrokeColor);
    mCircleStrokePaint.setStyle(Paint.Style.STROKE);
    mCircleStrokePaint.setStrokeWidth(1);

    mNumberTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mNumberTextPaint.setColor(textColor);
    mNumberTextPaint.setTextAlign(Paint.Align.CENTER);
    mNumberTextPaint.setTextSize(numberTextSize);

    mNumberStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mNumberStrokePaint.setColor(cellFillColor);
    mNumberStrokePaint.setTextAlign(Paint.Align.CENTER);
    mNumberStrokePaint.setTextSize(numberTextSize);
    mNumberStrokePaint.setStyle(Paint.Style.STROKE);
    mNumberStrokePaint.setStrokeWidth(NUMBER_TEXT_STROKE_WIDTH * dm.scaledDensity);

    mAnswerTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mAnswerTextPaint.setColor(textColor);
    mAnswerTextPaint.setTextSize(answerTextSize);
    mAnswerTextPaint.setTextAlign(Paint.Align.CENTER);

    // http://www.google.com/fonts/specimen/Kalam
    Typeface typeface = Typeface.createFromAsset(context.getAssets(), "kalam-regular.ttf");
    mAnswerTextPaint.setTypeface(typeface);

    // Init rest of the values
    mCircleRadius = (mCellSize / 2) - mCircleStrokePaint.getStrokeWidth();
    mPuzzleCells = EMPTY_CELLS;
    mPuzzleWidth = 0;
    mPuzzleHeight = 0;
    mAllowedChars = EMPTY_CHARS;

    mRenderScale = 0;
    mBitmapOffset = new PointF();
    mCenteredOffset = new PointF();
    mTranslationBounds = new RectF();

    mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
    mGestureDetector = new GestureDetector(context, new GestureListener());

    mContentRect = new RectF();
    mPuzzleRect = new RectF();

    mBitmapPaint = new Paint(Paint.FILTER_BITMAP_FLAG);

    mScroller = new Scroller(context, null, true);
    mZoomer = new Zoomer(context);

    setFocusableInTouchMode(true);
    setOnKeyListener(this);
}

From source file:com.raja.knowme.FragmentWorkExp.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View mHolderView = inflater.inflate(R.layout.fragment_work_exp, null);
    shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
    functions = new AppCommonFunctions(getActivity());
    pref = new AppPreferences(getActivity());
    knowmeData = new KnowMeDataObject(getActivity());
    mProgressDialog = new ProgressDialog(getActivity());
    mProgressDialog.setCancelable(false);
    mProgressDialog.setMessage(getString(R.string.loading));

    mCompanyNameSwitcher = (TextSwitcher) mHolderView.findViewById(R.id.work_company_name_text);
    mCompanySpanSwitcher = (TextSwitcher) mHolderView.findViewById(R.id.work_company_span_text);
    mCompanySummarySwitcher = (TextSwitcher) mHolderView.findViewById(R.id.work_company_summary_text);
    mScrollContainer = (ScrollView) mHolderView.findViewById(R.id.work_scrollview);
    mInstructionBtn = (RelativeLayout) mHolderView.findViewById(R.id.instrunstions_layout);

    if (!pref.getWorkFirstRun()) {
        mInstructionBtn.setVisibility(RelativeLayout.GONE);
    }//from ww w. j av a 2s . c  o m

    mInstructionBtn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            pref.setWorkRunned();
            mInstructionBtn.setVisibility(RelativeLayout.GONE);
        }
    });
    /*                 Multiple Screen Size Condition             */

    // Small Size

    if ((getContext().getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
        // Toast.makeText(getActivity(), "small", Toast.LENGTH_SHORT).show();
        mCompanyNameSwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 245, 242, 11));
                textSwitcher_text.setTextSize(24 * functions.getScreenDPI());
                textSwitcher_text.setSingleLine(true);
                textSwitcher_text.setEllipsize(TruncateAt.MARQUEE);
                textSwitcher_text.setMarqueeRepeatLimit(-1);
                textSwitcher_text.setHorizontallyScrolling(true);
                return textSwitcher_text;
            }
        });

        mCompanySpanSwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 245, 242, 11));
                textSwitcher_text.setTextSize(12 * functions.getScreenDPI());
                textSwitcher_text.setSingleLine(true);
                textSwitcher_text.setEllipsize(TruncateAt.MARQUEE);
                textSwitcher_text.setMarqueeRepeatLimit(-1);
                textSwitcher_text.setHorizontallyScrolling(true);
                return textSwitcher_text;
            }
        });

        mCompanySummarySwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 225, 225, 225));
                textSwitcher_text.setTextSize(6 * functions.getScreenDPI());
                return textSwitcher_text;
            }
        });
    }

    //Normal Size

    else if ((getContext().getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
        // Toast.makeText(getActivity(), "normal", Toast.LENGTH_SHORT).show();
        mCompanyNameSwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 245, 242, 11));
                textSwitcher_text.setTextSize(14 * functions.getScreenDPI());
                textSwitcher_text.setSingleLine(true);
                textSwitcher_text.setEllipsize(TruncateAt.MARQUEE);
                textSwitcher_text.setMarqueeRepeatLimit(-1);
                textSwitcher_text.setHorizontallyScrolling(true);
                return textSwitcher_text;
            }
        });

        mCompanySpanSwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 245, 242, 11));
                textSwitcher_text.setTextSize(10 * functions.getScreenDPI());
                textSwitcher_text.setSingleLine(true);
                textSwitcher_text.setEllipsize(TruncateAt.MARQUEE);
                textSwitcher_text.setMarqueeRepeatLimit(-1);
                textSwitcher_text.setHorizontallyScrolling(true);
                return textSwitcher_text;
            }
        });

        mCompanySummarySwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 225, 225, 225));
                textSwitcher_text.setTextSize(9 * functions.getScreenDPI());
                return textSwitcher_text;
            }
        });
    }

    // Large Size

    else if ((getContext().getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
        //  Toast.makeText(getActivity(), "large", Toast.LENGTH_SHORT).show();

        mCompanyNameSwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 245, 242, 11));
                textSwitcher_text.setTextSize(32 * functions.getScreenDPI());
                textSwitcher_text.setSingleLine(true);
                textSwitcher_text.setEllipsize(TruncateAt.MARQUEE);
                textSwitcher_text.setMarqueeRepeatLimit(-1);
                textSwitcher_text.setHorizontallyScrolling(true);
                return textSwitcher_text;
            }
        });

        mCompanySpanSwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 245, 242, 11));
                textSwitcher_text.setTextSize(24 * functions.getScreenDPI());
                textSwitcher_text.setSingleLine(true);
                textSwitcher_text.setEllipsize(TruncateAt.MARQUEE);
                textSwitcher_text.setMarqueeRepeatLimit(-1);
                textSwitcher_text.setHorizontallyScrolling(true);
                return textSwitcher_text;
            }
        });

        mCompanySummarySwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 225, 225, 225));
                textSwitcher_text.setTextSize(18 * functions.getScreenDPI());
                return textSwitcher_text;
            }
        });
    }

    //X-large Size

    else if ((getContext().getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
        //  Toast.makeText(getActivity(), "xlarge", Toast.LENGTH_SHORT).show();
        mCompanyNameSwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 245, 242, 11));
                textSwitcher_text.setTextSize(48 * functions.getScreenDPI());
                textSwitcher_text.setSingleLine(true);
                textSwitcher_text.setEllipsize(TruncateAt.MARQUEE);
                textSwitcher_text.setMarqueeRepeatLimit(-1);
                textSwitcher_text.setHorizontallyScrolling(true);
                return textSwitcher_text;
            }
        });

        mCompanySpanSwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 245, 242, 11));
                textSwitcher_text.setTextSize(32 * functions.getScreenDPI());
                textSwitcher_text.setSingleLine(true);
                textSwitcher_text.setEllipsize(TruncateAt.MARQUEE);
                textSwitcher_text.setMarqueeRepeatLimit(-1);
                textSwitcher_text.setHorizontallyScrolling(true);
                return textSwitcher_text;
            }
        });

        mCompanySummarySwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 225, 225, 225));
                textSwitcher_text.setTextSize(24 * functions.getScreenDPI());
                return textSwitcher_text;
            }
        });
    }

    //Undefined Size

    else {
        // Toast.makeText(getActivity(), "undefined", Toast.LENGTH_SHORT).show();

        mCompanyNameSwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 245, 242, 11));
                textSwitcher_text.setTextSize(19 * functions.getScreenDPI());
                textSwitcher_text.setSingleLine(true);
                textSwitcher_text.setEllipsize(TruncateAt.MARQUEE);
                textSwitcher_text.setMarqueeRepeatLimit(-1);
                textSwitcher_text.setHorizontallyScrolling(true);
                return textSwitcher_text;
            }
        });

        mCompanySpanSwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 245, 242, 11));
                textSwitcher_text.setTextSize(12 * functions.getScreenDPI());
                textSwitcher_text.setSingleLine(true);
                textSwitcher_text.setEllipsize(TruncateAt.MARQUEE);
                textSwitcher_text.setMarqueeRepeatLimit(-1);
                textSwitcher_text.setHorizontallyScrolling(true);
                return textSwitcher_text;
            }
        });

        mCompanySummarySwitcher.setFactory(new ViewFactory() {
            public View makeView() {
                /** Set up the custom auto scrolling text view class for lengthy album names */
                AppTextView textSwitcher_text = new AppTextView(getActivity());
                textSwitcher_text.setTextColor(Color.argb(225, 225, 225, 225));
                textSwitcher_text.setTextSize(12 * functions.getScreenDPI());
                return textSwitcher_text;
            }
        });
    }

    mProgressDialog.show();
    new LoadData().execute();

    // Gesture detection
    gestureDetector = new GestureDetector(getActivity(), new OnGestureListener() {

        public boolean onSingleTapUp(MotionEvent e) {
            return false;
        }

        public void onShowPress(MotionEvent e) {
        }

        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return false;
        }

        public void onLongPress(MotionEvent e) {
        }

        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                if (Math.abs(e1.getY() - e2.getY()) > AppGlobalVariables.SWIPE_MAX_OFF_PATH)
                    return false;
                /** Left swipe */
                if (e1.getX() - e2.getX() > AppGlobalVariables.SWIPE_MIN_DISTANCE
                        && Math.abs(velocityX) > AppGlobalVariables.SWIPE_THRESHOLD_VELOCITY) {
                    if (count < (MAX_COUNT - 1))
                        nextCompany();
                    else {
                        mCompanyNameSwitcher.startAnimation(shake);
                        mCompanySpanSwitcher.startAnimation(shake);
                        mCompanySummarySwitcher.startAnimation(shake);
                    }
                    /** Right Swipe */
                } else if (e2.getX() - e1.getX() > AppGlobalVariables.SWIPE_MIN_DISTANCE
                        && Math.abs(velocityX) > AppGlobalVariables.SWIPE_THRESHOLD_VELOCITY) {
                    if (count != 0)
                        previousComapny();
                    else {
                        mCompanyNameSwitcher.startAnimation(shake);
                        mCompanySpanSwitcher.startAnimation(shake);
                        mCompanySummarySwitcher.startAnimation(shake);
                    }
                }
            } catch (Exception e) {
            }

            return false;
        }

        public boolean onDown(MotionEvent e) {
            return false;
        }
    });

    gestureListener = new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            return gestureDetector.onTouchEvent(event);
        }
    };

    mScrollContainer.setOnTouchListener(gestureListener);
    return mHolderView;
}

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

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

    DisplayMetrics metrics = new DisplayMetrics();
    SherlockFragmentActivity activity = getSherlockActivity();

    activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

    displayPageNumber(-1); // Initializes the pagenumber view properly

    final GestureDetector gestureDetector = new GestureDetector(context,
            new NavGestureDetector(bookView, this, metrics));

    View.OnTouchListener gestureListener = new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {

            if (ttsIsRunning()) {
                return false;
            }/*from   w  w  w. j a v a 2  s  . c o  m*/

            return gestureDetector.onTouchEvent(event);
        }
    };

    this.viewSwitcher.setOnTouchListener(gestureListener);
    this.bookView.setOnTouchListener(gestureListener);
    this.dummyView.setOnTouchListener(gestureListener);

    registerForContextMenu(bookView);
    saveConfigState();

    Intent intent = activity.getIntent();
    String file = null;

    if (intent.getData() != null) {
        file = intent.getData().getPath();
    }

    if (file == null) {
        file = config.getLastOpenedFile();
    }

    updateFromPrefs();
    updateFileName(savedInstanceState, file);

    if ("".equals(fileName) || !new File(fileName).exists()) {

        LOG.info("Requested to open file " + fileName + ", which doesn't seem to exist. "
                + "Switching back to the library.");

        Intent newIntent = new Intent(context, LibraryActivity.class);
        startActivity(newIntent);
        activity.finish();
        return;

    } else {

        if (savedInstanceState == null && config.isSyncEnabled()) {
            new DownloadProgressTask().execute();
        } else {
            bookView.restore();
        }
    }

    if (ttsIsRunning()) {
        this.mediaLayout.setVisibility(View.VISIBLE);
        this.ttsPlaybackItemQueue.updateSpeechCompletedCallbacks(this);
        uiHandler.post(progressBarUpdater);
    }

    activity.getSupportActionBar().addOnMenuVisibilityListener(new ActionBar.OnMenuVisibilityListener() {
        @Override
        public void onMenuVisibilityChanged(boolean isVisible) {

            LOG.debug("Detected change of visibility in action-bar: visible=" + isVisible);

            if (isVisible) {
                titleBarLayout.setVisibility(View.VISIBLE);
            } else {
                titleBarLayout.setVisibility(View.GONE);
            }
        }
    });

    /*
    new ShakeListener(getActivity()).setOnShakeListener(new ShakeListener.OnShakeListener() {
    @Override
    public void onShake() {
        if ( ! ttsIsRunning() ) {
            startTextToSpeech();
        }
    }
    });
    */
}

From source file:com.wanikani.androidnotifier.graph.HistogramPlot.java

/**
 * Constructor//from ww  w. ja  v  a 2s .c  o  m
 * @param ctxt the context
 * @param attrs the attributes
 */
public HistogramPlot(Context ctxt, AttributeSet attrs) {
    super(ctxt, attrs);

    scroller = new Scroller(ctxt);
    glist = new GestureListener();
    gdect = new GestureDetector(ctxt, glist);

    loadAttributes(ctxt, attrs);
}