Example usage for android.view GestureDetector setOnDoubleTapListener

List of usage examples for android.view GestureDetector setOnDoubleTapListener

Introduction

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

Prototype

public void setOnDoubleTapListener(OnDoubleTapListener onDoubleTapListener) 

Source Link

Document

Sets the listener which will be called for double-tap and related gestures.

Usage

From source file:com.gmail.walles.johan.batterylogger.BatteryPlotFragment.java

private GestureDetector getOneFingerGestureDetector(final XYPlot plot) {
    GestureDetector.SimpleOnGestureListener gestureListener = new GestureDetector.SimpleOnGestureListener() {
        @Override//ww  w  .  j a v  a 2 s .c om
        public boolean onDown(MotionEvent motionEvent) {
            // Return true since the framework is weird:
            // http://stackoverflow.com/questions/4107565/on-android-do-gesture-events-work-on-the-emulator
            return true;
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            double targetMinX;
            double targetMaxX;
            if (minX == originalMinX && maxX == originalMaxX) {
                // Reset zoom to two most recent days
                targetMaxX = originalMaxX;
                targetMinX = targetMaxX - History.deltaMsToDouble(86400 * 1000 * 2);
            } else {
                // Reset zoom to max out
                targetMinX = originalMinX;
                targetMaxX = originalMaxX;
            }

            animateXrange(plot, targetMinX, targetMaxX);

            return true;
        }

        @Override
        public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent2, float dx, float dy) {
            scrollSideways(plot, dx);

            plot.setDomainBoundaries(minX, maxX, BoundaryMode.FIXED);
            redrawPlot(plot);
            return true;
        }
    };

    final GestureDetector gestureDetector = new GestureDetector(getActivity(), gestureListener);
    gestureDetector.setIsLongpressEnabled(false);
    gestureDetector.setOnDoubleTapListener(gestureListener);

    return gestureDetector;
}

From source file:com.farmerbb.taskbar.activity.HomeActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

    View view = new View(this);
    view.setOnClickListener(view1 -> LocalBroadcastManager.getInstance(HomeActivity.this)
            .sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_START_MENU")));

    view.setOnLongClickListener(view12 -> {
        setWallpaper();/*from  w  ww .  j a  va  2  s  . c o m*/
        return false;
    });

    view.setOnGenericMotionListener((view13, motionEvent) -> {
        if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS
                && motionEvent.getButtonState() == MotionEvent.BUTTON_SECONDARY) {
            setWallpaper();
        }
        return false;
    });

    final GestureDetector detector = new GestureDetector(this, 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) {
            final SharedPreferences pref = U.getSharedPreferences(HomeActivity.this);
            if (!pref.getBoolean("dont_show_double_tap_dialog", false)) {
                if (pref.getBoolean("double_tap_to_sleep", false)) {
                    U.lockDevice(HomeActivity.this);
                } else {
                    int theme = -1;
                    switch (pref.getString("theme", "light")) {
                    case "light":
                        theme = R.style.AppTheme;
                        break;
                    case "dark":
                        theme = R.style.AppTheme_Dark;
                        break;
                    }

                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            new ContextThemeWrapper(HomeActivity.this, theme));
                    builder.setTitle(R.string.double_tap_to_sleep)
                            .setMessage(R.string.enable_double_tap_to_sleep)
                            .setNegativeButton(
                                    pref.getBoolean("double_tap_dialog_shown", false)
                                            ? R.string.action_dont_show_again
                                            : R.string.action_cancel,
                                    (dialog, which) -> pref.edit()
                                            .putBoolean(pref.getBoolean("double_tap_dialog_shown", false)
                                                    ? "dont_show_double_tap_dialog"
                                                    : "double_tap_dialog_shown", true)
                                            .apply())
                            .setPositiveButton(R.string.action_ok, (dialog, which) -> {
                                pref.edit().putBoolean("double_tap_to_sleep", true).apply();
                                U.lockDevice(HomeActivity.this);
                            });

                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
            }

            return false;
        }

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

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

    });

    view.setOnTouchListener((v, event) -> {
        detector.onTouchEvent(event);
        return false;
    });

    setContentView(view);

    LocalBroadcastManager.getInstance(this).registerReceiver(killReceiver,
            new IntentFilter("com.farmerbb.taskbar.KILL_HOME_ACTIVITY"));
    LocalBroadcastManager.getInstance(this).registerReceiver(forceTaskbarStartReceiver,
            new IntentFilter("com.farmerbb.taskbar.FORCE_TASKBAR_RESTART"));
}

From source file:com.hippo.nimingban.ui.ListActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);

    mNMBClient = NMBApplication.getNMBClient(this);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    mSlidingDrawerLayout = (SlidingDrawerLayout) findViewById(R.id.drawer_layout);
    mContentLayout = (ContentLayout) mSlidingDrawerLayout.findViewById(R.id.content_layout);
    mRecyclerView = mContentLayout.getRecyclerView();
    mLeftDrawer = (LeftDrawer) mSlidingDrawerLayout.findViewById(R.id.left_drawer);
    mRightDrawer = (RightDrawer) mSlidingDrawerLayout.findViewById(R.id.right_drawer);

    final GestureDetector gestureDetector = new GestureDetector(this, new SimpleGestureListener());
    gestureDetector.setOnDoubleTapListener(new SimpleDoubleTapListener() {
        @Override/*  ww  w .  ja  va  2s. co m*/
        public boolean onDoubleTap(MotionEvent e) {
            mPostHelper.refresh();
            return true;
        }
    });
    toolbar.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            gestureDetector.onTouchEvent(event);
            return true;
        }
    });
    setSupportActionBar(toolbar);

    mDrawerToggle = new ActionBarDrawerToggle(this, mSlidingDrawerLayout, R.string.drawer_open,
            R.string.drawer_close) {

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            if (mLeftDrawer == drawerView) {
                super.onDrawerSlide(drawerView, slideOffset);
            }
        }

        private void setMenuItemVisible(MenuItem item, boolean visible) {
            if (item != null) {
                item.setVisible(visible);
            }
        }

        @Override
        public void onDrawerClosed(View view) {
            if (mLeftDrawer == view) {
                super.onDrawerClosed(view);
            }
            if (mRightDrawer == view) {
                setMenuItemVisible(mRule, true);
                setMenuItemVisible(mCreatePost, true);
                setMenuItemVisible(mRefresh, true);
                setMenuItemVisible(mSortForumsMenu, false);
            }
        }

        @Override
        public void onDrawerOpened(View view) {
            if (mLeftDrawer == view) {
                // Analysis
                Analysis.action(ListActivity.this, "open_left_drawer");

                super.onDrawerOpened(view);
            }
            if (mRightDrawer == view) {
                // Analysis
                Analysis.action(ListActivity.this, "open_right_drawer");

                setMenuItemVisible(mRule, false);
                setMenuItemVisible(mCreatePost, false);
                setMenuItemVisible(mRefresh, false);
                setMenuItemVisible(mSortForumsMenu, true);
            }
        }
    };
    mSlidingDrawerLayout.setDrawerListener(mDrawerToggle);

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
    }

    mSlidingDrawerLayout.setDrawerShadow(ContextCompat.getDrawable(this, R.drawable.drawer_shadow_left),
            Gravity.LEFT);
    mSlidingDrawerLayout.setDrawerShadow(ContextCompat.getDrawable(this, R.drawable.drawer_shadow_right),
            Gravity.RIGHT);
    mSlidingDrawerLayout.setStatusBarColor(ResourcesUtils.getAttrColor(this, R.attr.colorPrimaryDark));

    mPostHelper = new PostHelper();
    mPostHelper.setEmptyString(getString(R.string.no_post));
    mContentLayout.setHelper(mPostHelper);
    if (Settings.getFastScroller()) {
        mContentLayout.showFastScroll();
    } else {
        mContentLayout.hideFastScroll();
    }

    mPostAdapter = new PostAdapter();
    mRecyclerView.setAdapter(mPostAdapter);
    mRecyclerView
            .setSelector(RippleSalon.generateRippleDrawable(ResourcesUtils.getAttrBoolean(this, R.attr.dark)));
    mRecyclerView.setDrawSelectorOnTop(true);
    mRecyclerView.setOnItemClickListener(new ClickPostListener());
    mRecyclerView.hasFixedSize();
    mRecyclerView.setClipToPadding(false);

    int halfInterval = getResources().getDimensionPixelOffset(R.dimen.card_interval) / 2;
    if (getResources().getBoolean(R.bool.two_way)) {
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        mRecyclerView.addItemDecoration(new MarginItemDecoration(halfInterval));
        mRecyclerView.setPadding(halfInterval, halfInterval, halfInterval, halfInterval);
        mRecyclerView.setItemAnimator(new FloatItemAnimator(mRecyclerView));
    } else {
        mRecyclerView.addItemDecoration(new MarginItemDecoration(0, halfInterval, 0, halfInterval));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setPadding(0, halfInterval, 0, halfInterval);
    }

    mLeftDrawer.setHelper(this);

    mRightDrawer.setRightDrawerHelper(this);

    if (savedInstanceState == null) {
        int ils = Settings.getImageLoadingStrategy();
        if (ils == Settings.IMAGE_LOADING_STRATEGY_ALL || (ils == Settings.IMAGE_LOADING_STRATEGY_WIFI
                && NMBApplication.isConnectedWifi(ListActivity.this))) {
            mLeftDrawer.loadHeaderImageView();
        }
    }

    updateForums(true);

    checkForAppStart();

    Messenger.getInstance().register(Constants.MESSENGER_ID_CREATE_POST, this);
    Messenger.getInstance().register(Constants.MESSENGER_ID_FAST_SCROLLER, this);

    // Check permission
    PermissionRequester.request(this, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            getString(R.string.write_storage_permission_tip), PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);

    if (Settings.getGuideListActivity()) {
        showLeftDrawerGuide();
    }
}

From source file:com.notepadlite.NoteViewFragment.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override/*from  w ww.java  2 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) {
        ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(title, null,
                getResources().getColor(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
    noteContents = (TextView) getActivity().findViewById(R.id.textView);

    // 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");

    if (theme.contains("light")) {
        noteContents.setTextColor(getResources().getColor(R.color.text_color_primary));
        noteContents.setBackgroundColor(getResources().getColor(R.color.window_background));
        scrollView.setBackgroundColor(getResources().getColor(R.color.window_background));
    }

    if (theme.contains("dark")) {
        noteContents.setTextColor(getResources().getColor(R.color.text_color_primary_dark));
        noteContents.setBackgroundColor(getResources().getColor(R.color.window_background_dark));
        scrollView.setBackgroundColor(getResources().getColor(R.color.window_background_dark));
    }

    if (theme.contains("sans"))
        noteContents.setTypeface(Typeface.SANS_SERIF);

    if (theme.contains("serif"))
        noteContents.setTypeface(Typeface.SERIF);

    if (theme.contains("monospace"))
        noteContents.setTypeface(Typeface.MONOSPACE);

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

    // 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
    noteContents.setText(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;
        }

    });

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

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

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override// w  w  w.  j av a2 s.c om
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.anjalimacwan.fragment.NoteViewFragment.java

@SuppressLint("SetJavaScriptEnabled")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override/*from www .  j a  v  a  2 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) {
        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;
            }
        });
}