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:ticwear.design.widget.FloatingActionButton.java

public void startDelayConfirmation(long delay, DelayedConfirmationListener listener) {
    stopDelayConfirmation();// w w w. j  av  a 2  s .  c  o  m

    setProgressMode(CircularProgressDrawable.MODE_DETERMINATE);
    setProgressPercent(0);
    setShowProgress(true);

    setClickable(true);

    mDelayedConfirmationListener = listener;
    mDelayedConfirmationAnimator = ValueAnimator.ofFloat(0, 1).setDuration(delay);
    mDelayedConfirmationAnimator.addUpdateListener(new AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            float progress = (float) animation.getAnimatedValue();
            if (getProgressDrawable() != null) {
                getProgressDrawable().setProgress(progress);
            } else {
                stopDelayConfirmation();
            }
            if (progress >= 1) {
                finishDelayConfirmation(false);
            }
        }
    });
    mDelayedConfirmationAnimator.start();

    if (mGestureDetector == null) {
        mGestureDetector = new GestureDetector(getContext(), new SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                finishDelayConfirmation(true);
                return super.onSingleTapConfirmed(e);
            }
        });
    }
}

From source file:com.android.ex.chips.RecipientEditTextView.java

public RecipientEditTextView(final Context context, final AttributeSet attrs) {
    super(context, attrs);
    mAddTextWatcher = new Runnable() {
        @Override//w  w w.  ja v  a 2s.  c  om
        public void run() {
            if (mTextWatcher == null) {
                mTextWatcher = new RecipientTextWatcher();
                addTextChangedListener(mTextWatcher);
            }
        }
    };
    mDelayedShrink = new Runnable() {
        @Override
        public void run() {
            shrink();
        }
    };
    mHandlePendingChips = new Runnable() {
        @Override
        public void run() {
            handlePendingChips();
        }
    };
    setChipDimensions(context, attrs);
    if (sSelectedTextColor == -1)
        sSelectedTextColor = ContextCompat.getColor(context, android.R.color.white);
    /*mAlternatesPopup=new ListPopupWindow(context);
    mAddressPopup=new ListPopupWindow(context);*/
    mCopyDialog = new Dialog(context);
    mAlternatesListener = new OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> adapterView, final View view, final int position,
                final long rowId) {
            //mAlternatesPopup.setOnItemClickListener(null);
            replaceChip(mSelectedChip,
                    ((RecipientAlternatesAdapter) adapterView.getAdapter()).getRecipientEntry(position));
            final Message delayed = Message.obtain(mHandler, DISMISS);
            //delayed.obj=mAlternatesPopup;
            mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
            clearComposingText();
        }
    };
    setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    setOnItemClickListener(null);
    setCustomSelectionActionModeCallback(this);
    mHandler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            if (msg.what == DISMISS) {
                //((ListPopupWindow)msg.obj).dismiss();
                return;
            }
            super.handleMessage(msg);
        }
    };
    mTextWatcher = new RecipientTextWatcher();
    addTextChangedListener(mTextWatcher);
    mGestureDetector = new GestureDetector(context, this);
    setOnEditorActionListener(this);
}

From source file:com.vonglasow.michael.satstat.MapSectionFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mainActivity = (MainActivity) this.getContext();
    View rootView = inflater.inflate(R.layout.fragment_main_map, container, false);

    mapReattach = (ImageButton) rootView.findViewById(R.id.mapReattach);

    mapReattach.setVisibility(View.GONE);
    isMapViewAttached = true;//from w  w w  . ja v  a2 s  . co  m

    OnClickListener clis = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == mapReattach) {
                isMapViewAttached = true;
                mapReattach.setVisibility(View.GONE);
                updateMap();
            }
        }
    };
    mapReattach.setOnClickListener(clis);

    // Initialize controls
    mapMap = new MapView(rootView.getContext());
    ((FrameLayout) rootView).addView(mapMap, 0);

    mapMap.setClickable(true);
    mapMap.getMapScaleBar().setVisible(true);
    mapMap.setBuiltInZoomControls(true);
    mapMap.getMapZoomControls().setZoomLevelMin((byte) 10);
    mapMap.getMapZoomControls().setZoomLevelMax((byte) 20);

    providerLocations = new HashMap<String, Location>();

    mAvailableProviderStyles = new ArrayList<String>(Arrays.asList(LOCATION_PROVIDER_STYLES));

    providerStyles = new HashMap<String, String>();
    providerAppliedStyles = new HashMap<String, String>();

    providerInvalidationHandler = new Handler();
    providerInvalidators = new HashMap<String, Runnable>();

    if (mapTileCache == null)
        mapTileCache = PersistentTileCache.createTileCache(rootView.getContext(), "MapQuest",
                mapMap.getModel().displayModel.getTileSize(), 1f,
                mapMap.getModel().frameBufferModel.getOverdrawFactor());

    onlineTileSource = new OnlineTileSource(
            new String[] { "otile1.mqcdn.com", "otile2.mqcdn.com", "otile3.mqcdn.com", "otile4.mqcdn.com" },
            80);
    onlineTileSource.setName("MapQuest").setAlpha(false).setBaseUrl("/tiles/1.0.0/map/").setExtension("png")
            .setParallelRequestsLimit(8).setProtocol("http").setTileSize(256).setZoomLevelMax((byte) 18)
            .setZoomLevelMin((byte) 0);

    GestureDetector gd = new GestureDetector(rootView.getContext(),
            new GestureDetector.SimpleOnGestureListener() {
                public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                    mapReattach.setVisibility(View.VISIBLE);
                    isMapViewAttached = false;
                    return false;
                }
            });

    mapMap.setGestureDetector(gd);

    mainActivity.mapSectionFragment = this;

    return rootView;
}

From source file:org.odk.collect.android.activities.FormEntryActivity.java

/**
 * Called when the activity is first created.
 *//*from   www  . ja v  a2s. c  o m*/
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // must be at the beginning of any activity that can be called from an
    // external intent
    try {
        Collect.createODKDirs();
    } catch (RuntimeException e) {
        createErrorDialog(e.getMessage(), EXIT);
        return;
    }

    setContentView(R.layout.form_entry);

    formsDao = new FormsDao();

    errorMessage = null;

    beenSwiped = false;
    alertDialog = null;
    currentView = null;
    inAnimation = null;
    outAnimation = null;
    gestureDetector = new GestureDetector(this, this);
    questionHolder = (LinearLayout) findViewById(R.id.questionholder);

    hasHardwareMenu = ViewConfigurationCompat
            .hasPermanentMenuKey(ViewConfiguration.get(getApplicationContext()));

    // get admin preference settings
    adminPreferences = getSharedPreferences(AdminPreferencesActivity.ADMIN_PREFERENCES, 0);

    initToolbar();

    nextButton = (ImageButton) findViewById(R.id.form_forward_button);
    nextButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            beenSwiped = true;
            showNextView();
        }
    });

    backButton = (ImageButton) findViewById(R.id.form_back_button);
    backButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            beenSwiped = true;
            showPreviousView();
        }
    });

    String startingXPath = null;
    String waitingXPath = null;
    String instancePath = null;
    Boolean newForm = true;
    autoSaved = false;
    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(KEY_FORMPATH)) {
            formPath = savedInstanceState.getString(KEY_FORMPATH);
        }
        if (savedInstanceState.containsKey(KEY_INSTANCEPATH)) {
            instancePath = savedInstanceState.getString(KEY_INSTANCEPATH);
        }
        if (savedInstanceState.containsKey(KEY_XPATH)) {
            startingXPath = savedInstanceState.getString(KEY_XPATH);
            Timber.i("startingXPath is: %s", startingXPath);
        }
        if (savedInstanceState.containsKey(KEY_XPATH_WAITING_FOR_DATA)) {
            waitingXPath = savedInstanceState.getString(KEY_XPATH_WAITING_FOR_DATA);
            Timber.i("waitingXPath is: %s", waitingXPath);
        }
        if (savedInstanceState.containsKey(NEWFORM)) {
            newForm = savedInstanceState.getBoolean(NEWFORM, true);
        }
        if (savedInstanceState.containsKey(KEY_ERROR)) {
            errorMessage = savedInstanceState.getString(KEY_ERROR);
        }
        if (savedInstanceState.containsKey(KEY_AUTO_SAVED)) {
            autoSaved = savedInstanceState.getBoolean(KEY_AUTO_SAVED);
        }
    }

    // If a parse error message is showing then nothing else is loaded
    // Dialogs mid form just disappear on rotation.
    if (errorMessage != null) {
        createErrorDialog(errorMessage, EXIT);
        return;
    }

    // Check to see if this is a screen flip or a new form load.
    Object data = getLastCustomNonConfigurationInstance();
    if (data instanceof FormLoaderTask) {
        formLoaderTask = (FormLoaderTask) data;
    } else if (data instanceof SaveToDiskTask) {
        saveToDiskTask = (SaveToDiskTask) data;
    } else if (data == null) {
        if (!newForm) {
            if (Collect.getInstance().getFormController() != null) {
                refreshCurrentView();
            } else {
                Timber.w("Reloading form and restoring state.");
                // we need to launch the form loader to load the form
                // controller...
                formLoaderTask = new FormLoaderTask(instancePath, startingXPath, waitingXPath);
                Collect.getInstance().getActivityLogger().logAction(this, "formReloaded", formPath);
                // TODO: this doesn' work (dialog does not get removed):
                // showDialog(PROGRESS_DIALOG);
                // show dialog before we execute...
                formLoaderTask.execute(formPath);
            }
            return;
        }

        // Not a restart from a screen orientation change (or other).
        Collect.getInstance().setFormController(null);
        supportInvalidateOptionsMenu();

        Intent intent = getIntent();
        if (intent != null) {
            Uri uri = intent.getData();

            if (uri != null && getContentResolver().getType(uri).equals(InstanceColumns.CONTENT_ITEM_TYPE)) {
                // get the formId and version for this instance...
                String jrFormId = null;
                String jrVersion = null;
                {
                    Cursor instanceCursor = null;
                    try {
                        instanceCursor = getContentResolver().query(uri, null, null, null, null);
                        if (instanceCursor.getCount() != 1) {
                            this.createErrorDialog(getString(R.string.bad_uri, uri), EXIT);
                            return;
                        } else {
                            instanceCursor.moveToFirst();
                            instancePath = instanceCursor.getString(
                                    instanceCursor.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
                            Collect.getInstance().getActivityLogger().logAction(this, "instanceLoaded",
                                    instancePath);

                            jrFormId = instanceCursor
                                    .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
                            int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION);

                            jrVersion = instanceCursor.isNull(idxJrVersion) ? null
                                    : instanceCursor.getString(idxJrVersion);
                        }
                    } finally {
                        if (instanceCursor != null) {
                            instanceCursor.close();
                        }
                    }
                }

                String[] selectionArgs;
                String selection;

                if (jrVersion == null) {
                    selectionArgs = new String[] { jrFormId };
                    selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + " IS NULL";
                } else {
                    selectionArgs = new String[] { jrFormId, jrVersion };
                    selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + "=?";
                }

                {
                    Cursor formCursor = null;
                    try {
                        formCursor = formsDao.getFormsCursor(selection, selectionArgs);
                        if (formCursor.getCount() == 1) {
                            formCursor.moveToFirst();
                            formPath = formCursor
                                    .getString(formCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH));
                        } else if (formCursor.getCount() < 1) {
                            this.createErrorDialog(
                                    getString(R.string.parent_form_not_present, jrFormId)
                                            + ((jrVersion == null) ? ""
                                                    : "\n" + getString(R.string.version) + " " + jrVersion),
                                    EXIT);
                            return;
                        } else if (formCursor.getCount() > 1) {
                            // still take the first entry, but warn that
                            // there are multiple rows.
                            // user will need to hand-edit the SQLite
                            // database to fix it.
                            formCursor.moveToFirst();
                            formPath = formCursor
                                    .getString(formCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH));
                            this.createErrorDialog(getString(R.string.survey_multiple_forms_error), EXIT);
                            return;
                        }
                    } finally {
                        if (formCursor != null) {
                            formCursor.close();
                        }
                    }
                }
            } else if (uri != null
                    && getContentResolver().getType(uri).equals(FormsColumns.CONTENT_ITEM_TYPE)) {
                Cursor c = null;
                try {
                    c = getContentResolver().query(uri, null, null, null, null);
                    if (c.getCount() != 1) {
                        this.createErrorDialog(getString(R.string.bad_uri, uri), EXIT);
                        return;
                    } else {
                        c.moveToFirst();
                        formPath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
                        // This is the fill-blank-form code path.
                        // See if there is a savepoint for this form that
                        // has never been
                        // explicitly saved
                        // by the user. If there is, open this savepoint
                        // (resume this filled-in
                        // form).
                        // Savepoints for forms that were explicitly saved
                        // will be recovered
                        // when that
                        // explicitly saved instance is edited via
                        // edit-saved-form.
                        final String filePrefix = formPath.substring(formPath.lastIndexOf('/') + 1,
                                formPath.lastIndexOf('.')) + "_";
                        final String fileSuffix = ".xml.save";
                        File cacheDir = new File(Collect.CACHE_PATH);
                        File[] files = cacheDir.listFiles(new FileFilter() {
                            @Override
                            public boolean accept(File pathname) {
                                String name = pathname.getName();
                                return name.startsWith(filePrefix) && name.endsWith(fileSuffix);
                            }
                        });
                        // see if any of these savepoints are for a
                        // filled-in form that has never been
                        // explicitly saved by the user...
                        for (int i = 0; i < files.length; ++i) {
                            File candidate = files[i];
                            String instanceDirName = candidate.getName().substring(0,
                                    candidate.getName().length() - fileSuffix.length());
                            File instanceDir = new File(
                                    Collect.INSTANCES_PATH + File.separator + instanceDirName);
                            File instanceFile = new File(instanceDir, instanceDirName + ".xml");
                            if (instanceDir.exists() && instanceDir.isDirectory() && !instanceFile.exists()) {
                                // yes! -- use this savepoint file
                                instancePath = instanceFile.getAbsolutePath();
                                break;
                            }
                        }
                    }
                } finally {
                    if (c != null) {
                        c.close();
                    }
                }
            } else {
                Timber.e("Unrecognized URI: %s", uri);
                this.createErrorDialog(getString(R.string.unrecognized_uri, uri), EXIT);
                return;
            }

            formLoaderTask = new FormLoaderTask(instancePath, null, null);
            Collect.getInstance().getActivityLogger().logAction(this, "formLoaded", formPath);
            showDialog(PROGRESS_DIALOG);
            // show dialog before we execute...
            formLoaderTask.execute(formPath);
        }
    }
}

From source file:org.zirco.ui.activities.MainActivity.java

/**
 * Create main UI.//from   w  w  w .  j a va2 s  .c o m
 */
private void buildComponents() {

    mToolsActionGrid = new QuickActionGrid(this);
    mToolsActionGrid.addQuickAction(new QuickAction(this, R.drawable.ic_btn_home, R.string.QuickAction_Home));
    mToolsActionGrid.addQuickAction(new QuickAction(this, R.drawable.ic_btn_share, R.string.QuickAction_Share));
    mToolsActionGrid
            .addQuickAction(new QuickAction(this, R.drawable.ic_btn_select, R.string.QuickAction_SelectText));
    mToolsActionGrid.addQuickAction(
            new QuickAction(this, R.drawable.ic_btn_mobile_view, R.string.QuickAction_MobileView));

    mToolsActionGrid.setOnQuickActionClickListener(new OnQuickActionClickListener() {
        @Override
        public void onQuickActionClicked(QuickActionWidget widget, int position) {
            switch (position) {
            case 0:
                navigateToHome();
                break;
            case 1:
                ApplicationUtils.sharePage(MainActivity.this, mCurrentWebView.getTitle(),
                        mCurrentWebView.getUrl());
                break;
            case 2:
                swithToSelectAndCopyTextMode();
                break;
            case 3:
                String currentUrl = mUrlEditText.getText().toString();

                // Do not reload mobile view if already on it.
                if (!currentUrl.startsWith(Constants.URL_GOOGLE_MOBILE_VIEW_NO_FORMAT)) {
                    String url = String.format(Constants.URL_GOOGLE_MOBILE_VIEW,
                            mUrlEditText.getText().toString());
                    navigateToUrl(url);
                }
                break;
            }
        }
    });

    mToolsActionGrid.setOnDismissListener(new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            mToolsActionGridVisible = false;
            startToolbarsHideRunnable();
        }
    });

    mGestureDetector = new GestureDetector(this, new GestureListener());

    mUrlBarVisible = true;

    mWebViews = new ArrayList<CustomWebView>();
    Controller.getInstance().setWebViewList(mWebViews);

    mBubbleRightView = (ImageView) findViewById(R.id.BubbleRightView);
    mBubbleRightView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setToolbarsVisibility(true);
        }
    });
    mBubbleRightView.setVisibility(View.GONE);

    mBubbleLeftView = (ImageView) findViewById(R.id.BubbleLeftView);
    mBubbleLeftView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setToolbarsVisibility(true);
        }
    });
    mBubbleLeftView.setVisibility(View.GONE);

    mViewPager = (CustomViewPager) findViewById(R.id.ViewPager);
    mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
            Log.d("onPageSelected", Integer.toString(arg0));
            CustomWebView oldWebView = mPagerAdapter.getWebViewAtIndex(mCurrentDisplayedViewIndex);
            mCurrentDisplayedViewIndex = arg0;
            mCurrentWebView = mPagerAdapter.getWebViewAtIndex(mCurrentDisplayedViewIndex);

            oldWebView.doOnPause();
            mCurrentWebView.doOnResume();

            startToolbarsHideRunnable();

            showToastOnTabSwitch();

            updatePreviousNextTabViewsVisibility();
            updateUI();
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });

    mPagerAdapter = new CustomPagerAdapter(this, mViewPager);
    mViewPager.setAdapter(mPagerAdapter);

    mTopBar = (LinearLayout) findViewById(R.id.BarLayout);
    mTopBar.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // Dummy event to steel it from the WebView, in case of clicking between the buttons.            
        }
    });

    mBottomBar = (LinearLayout) findViewById(R.id.BottomBarLayout);
    mBottomBar.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // Dummy event to steel it from the WebView, in case of clicking between the buttons.            
        }
    });

    mPreviousTabView = (ImageView) findViewById(R.id.PreviousTabView);
    mPreviousTabView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showPreviousTab(true);
        }
    });
    mPreviousTabView.setVisibility(View.GONE);

    mNextTabView = (ImageView) findViewById(R.id.NextTabView);
    mNextTabView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showNextTab(true);
        }
    });
    mNextTabView.setVisibility(View.GONE);

    String[] from = new String[] { UrlSuggestionCursorAdapter.URL_SUGGESTION_TITLE,
            UrlSuggestionCursorAdapter.URL_SUGGESTION_URL };
    int[] to = new int[] { R.id.AutocompleteTitle, R.id.AutocompleteUrl };

    UrlSuggestionCursorAdapter adapter = new UrlSuggestionCursorAdapter(this, R.layout.url_autocomplete_line,
            null, from, to);

    adapter.setCursorToStringConverter(new CursorToStringConverter() {
        @Override
        public CharSequence convertToString(Cursor cursor) {
            String aColumnString = cursor
                    .getString(cursor.getColumnIndex(UrlSuggestionCursorAdapter.URL_SUGGESTION_URL));
            return aColumnString;
        }
    });

    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        @Override
        public Cursor runQuery(CharSequence constraint) {
            if ((constraint != null) && (constraint.length() > 0)) {
                return BookmarksProviderWrapper.getUrlSuggestions(getContentResolver(), constraint.toString(),
                        PreferenceManager.getDefaultSharedPreferences(MainActivity.this)
                                .getBoolean(Constants.PREFERENCE_USE_WEAVE, false));
            } else {
                return BookmarksProviderWrapper.getUrlSuggestions(getContentResolver(), null,
                        PreferenceManager.getDefaultSharedPreferences(MainActivity.this)
                                .getBoolean(Constants.PREFERENCE_USE_WEAVE, false));
            }
        }
    });

    mUrlEditText = (AutoCompleteTextView) findViewById(R.id.UrlText);
    mUrlEditText.setThreshold(1);
    mUrlEditText.setAdapter(adapter);

    mUrlEditText.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                navigateToUrl();
                return true;
            }

            return false;
        }

    });

    mUrlTextWatcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void afterTextChanged(Editable arg0) {
            updateGoButton();
        }
    };

    mUrlEditText.addTextChangedListener(mUrlTextWatcher);

    mUrlEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // Select all when focus gained.
            if (hasFocus) {
                mUrlEditText.setSelection(0, mUrlEditText.getText().length());
            }
        }
    });

    mUrlEditText.setCompoundDrawablePadding(5);

    mGoButton = (ImageButton) findViewById(R.id.GoBtn);
    mGoButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

            if (mCurrentWebView.isLoading()) {
                mCurrentWebView.stopLoading();
            } else if (!mCurrentWebView.isSameUrl(mUrlEditText.getText().toString())) {
                navigateToUrl();
            } else {
                mCurrentWebView.reload();
            }
        }
    });

    mToolsButton = (ImageButton) findViewById(R.id.ToolsBtn);
    mToolsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mToolsActionGridVisible = true;
            mToolsActionGrid.show(v);
        }
    });

    mProgressBar = (ProgressBar) findViewById(R.id.WebViewProgress);
    mProgressBar.setMax(100);

    mPreviousButton = (ImageButton) findViewById(R.id.PreviousBtn);
    mNextButton = (ImageButton) findViewById(R.id.NextBtn);

    mPreviousButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            navigatePrevious();
        }
    });

    mNextButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            navigateNext();
        }
    });

    mNewTabButton = (ImageButton) findViewById(R.id.NewTabBtn);
    mNewTabButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            addTab(true, mCurrentDisplayedViewIndex + 1);
        }
    });

    mRemoveTabButton = (ImageButton) findViewById(R.id.RemoveTabBtn);
    mRemoveTabButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            removeCurrentTab();
        }
    });

    mQuickButton = (ImageButton) findViewById(R.id.QuickBtn);
    mQuickButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onQuickButton();
        }
    });

}

From source file:taylorandtanner.gasscanmk1.OcrCaptureActivity.java

/**
 * Initializes the UI and creates the detector pipeline.
 *//*from  w  ww  . java2  s  .c o  m*/
@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.ocr_capture);

    Button next = (Button) findViewById(R.id.button3);
    next.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent myIntent = new Intent(view.getContext(), MainActivity.class);
            startActivityForResult(myIntent, 0);
        }

    });
    TextView tv1 = (TextView) findViewById(R.id.forStation);
    TextView tv1a = (TextView) findViewById(R.id.station);
    TextView tv2 = (TextView) findViewById(R.id.forPrice);
    TextView tv2a = (TextView) findViewById(R.id.totalPrice);
    TextView tv3 = (TextView) findViewById(R.id.forGallons);
    TextView tv3a = (TextView) findViewById(R.id.gallons);
    TextView tv4 = (TextView) findViewById(R.id.forPriceGal);
    TextView tv4a = (TextView) findViewById(R.id.priceGal);
    TextView tv5 = (TextView) findViewById(R.id.forMileage);
    TextView tv5a = (TextView) findViewById(R.id.mileage);

    tv1.setTextColor(Color.RED);
    tv1a.setTextColor(Color.BLACK);
    //Set others black
    tv3.setTextColor(Color.argb(0, 0, 0, 0));
    tv4.setTextColor(Color.argb(0, 0, 0, 0));
    tv5.setTextColor(Color.argb(0, 0, 0, 0));
    tv2.setTextColor(Color.argb(0, 0, 0, 0));
    tv3a.setTextColor(Color.argb(0, 0, 0, 0));
    tv4a.setTextColor(Color.argb(0, 0, 0, 0));
    tv5a.setTextColor(Color.argb(0, 0, 0, 0));
    tv2a.setTextColor(Color.argb(0, 0, 0, 0));

    final Button acceptOCRButton = (Button) findViewById(R.id.acceptOCRButton);
    acceptOCRButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("CLICKED!!1");

            String outputGal = ((TextView) findViewById(R.id.forGallons)).getText().toString();
            String outputPriceGal = ((TextView) findViewById(R.id.forPriceGal)).getText().toString();
            String outputMileage = ((TextView) findViewById(R.id.forMileage)).getText().toString();
            String outputPrice = ((TextView) findViewById(R.id.forPrice)).getText().toString();
            String outputStation = ((TextView) findViewById(R.id.forStation)).getText().toString();
            ReceiptEntry outputReceipt = new ReceiptEntry(outputPrice, outputGal, outputPriceGal, outputMileage,
                    "unassigned", outputStation);

            SerializeMethod(outputReceipt);
            // Intent activityChangeIntent = new Intent(OcrCaptureActivity.this, ReceiptForm.class);
            // OcrCaptureActivity.this.startActivity(activityChangeIntent);

        }
    });

    final SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // TODO Auto-generated method stub

            TextView t1 = (TextView) findViewById(R.id.forStation);
            TextView t1a = (TextView) findViewById(R.id.station);
            TextView t2 = (TextView) findViewById(R.id.forPrice);
            TextView t2a = (TextView) findViewById(R.id.totalPrice);
            TextView t3 = (TextView) findViewById(R.id.forGallons);
            TextView t3a = (TextView) findViewById(R.id.gallons);
            TextView t4 = (TextView) findViewById(R.id.forPriceGal);
            TextView t4a = (TextView) findViewById(R.id.priceGal);
            TextView t5 = (TextView) findViewById(R.id.forMileage);
            TextView t5a = (TextView) findViewById(R.id.mileage);

            if (seekBar.getProgress() >= 0 && seekBar.getProgress() < 20) {
                if (t1.getText().toString().equals("00"))
                    t1.setTextColor(Color.RED);
                else
                    t1.setTextColor(Color.BLUE);
                t1a.setTextColor(Color.BLACK);
                //Set others black
                t3.setTextColor(Color.argb(0, 0, 0, 0));
                t4.setTextColor(Color.argb(0, 0, 0, 0));
                t5.setTextColor(Color.argb(0, 0, 0, 0));
                t2.setTextColor(Color.argb(0, 0, 0, 0));
                t3a.setTextColor(Color.argb(0, 0, 0, 0));
                t4a.setTextColor(Color.argb(0, 0, 0, 0));
                t5a.setTextColor(Color.argb(0, 0, 0, 0));
                t2a.setTextColor(Color.argb(0, 0, 0, 0));
            }
            if (seekBar.getProgress() >= 20 && seekBar.getProgress() < 40) {
                if (t2.getText().toString().equals("00"))
                    t2.setTextColor(Color.RED);
                else
                    t2.setTextColor(Color.BLUE);
                t2a.setTextColor(Color.BLACK);
                //Set others black
                t3.setTextColor(Color.argb(0, 0, 0, 0));
                t4.setTextColor(Color.argb(0, 0, 0, 0));
                t5.setTextColor(Color.argb(0, 0, 0, 0));
                t1.setTextColor(Color.argb(0, 0, 0, 0));
                t3a.setTextColor(Color.argb(0, 0, 0, 0));
                t4a.setTextColor(Color.argb(0, 0, 0, 0));
                t5a.setTextColor(Color.argb(0, 0, 0, 0));
                t1a.setTextColor(Color.argb(0, 0, 0, 0));
            } else if (seekBar.getProgress() >= 40 && seekBar.getProgress() < 60) {
                if (t3.getText().toString().equals("00"))
                    t3.setTextColor(Color.RED);
                else
                    t3.setTextColor(Color.BLUE);
                t3a.setTextColor(Color.BLACK);
                //Set others black
                t2.setTextColor(Color.argb(0, 0, 0, 0));
                t4.setTextColor(Color.argb(0, 0, 0, 0));
                t5.setTextColor(Color.argb(0, 0, 0, 0));
                t1.setTextColor(Color.argb(0, 0, 0, 0));
                t2a.setTextColor(Color.argb(0, 0, 0, 0));
                t4a.setTextColor(Color.argb(0, 0, 0, 0));
                t5a.setTextColor(Color.argb(0, 0, 0, 0));
                t1a.setTextColor(Color.argb(0, 0, 0, 0));
            } else if (seekBar.getProgress() >= 60 && seekBar.getProgress() < 80) {
                if (t4.getText().toString().equals("00"))
                    t4.setTextColor(Color.RED);
                else
                    t4.setTextColor(Color.BLUE);
                t4a.setTextColor(Color.BLACK);
                //Set others black
                t2.setTextColor(Color.argb(0, 0, 0, 0));
                t3.setTextColor(Color.argb(0, 0, 0, 0));
                t5.setTextColor(Color.argb(0, 0, 0, 0));
                t1.setTextColor(Color.argb(0, 0, 0, 0));
                t2a.setTextColor(Color.argb(0, 0, 0, 0));
                t3a.setTextColor(Color.argb(0, 0, 0, 0));
                t5a.setTextColor(Color.argb(0, 0, 0, 0));
                t1a.setTextColor(Color.argb(0, 0, 0, 0));
            } else if (seekBar.getProgress() >= 80 && seekBar.getProgress() <= 100) {
                if (t5.getText().toString().equals("00"))
                    t5.setTextColor(Color.RED);
                else
                    t5.setTextColor(Color.BLUE);
                t5a.setTextColor(Color.BLACK);
                //Set others black
                t2.setTextColor(Color.argb(0, 0, 0, 0));
                t4.setTextColor(Color.argb(0, 0, 0, 0));
                t3.setTextColor(Color.argb(0, 0, 0, 0));
                t1.setTextColor(Color.argb(0, 0, 0, 0));
                t2a.setTextColor(Color.argb(0, 0, 0, 0));
                t4a.setTextColor(Color.argb(0, 0, 0, 0));
                t3a.setTextColor(Color.argb(0, 0, 0, 0));
                t1a.setTextColor(Color.argb(0, 0, 0, 0));
            }

        }
    });

    mPreview = (CameraSourcePreview) findViewById(R.id.preview);
    mGraphicOverlay = (GraphicOverlay<OcrGraphic>) findViewById(R.id.graphicOverlay);

    // Set good defaults for capturing text.
    boolean autoFocus = true;
    boolean useFlash = false;

    // Check for the camera permission before accessing the camera.  If the
    // permission is not granted yet, request permission.
    int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if (rc == PackageManager.PERMISSION_GRANTED) {
        createCameraSource(autoFocus, useFlash);
    } else {
        requestCameraPermission();
    }

    gestureDetector = new GestureDetector(this, new CaptureGestureListener());
    scaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());

    /*Snackbar.make(mGraphicOverlay, "Tap the text to place into the desired field. \n Select" +
        " 'confirm' when you are happy with the selection.",
        Snackbar.LENGTH_LONG)
        .show();*/

    // Set up the Text To Speech engine.
    /* TextToSpeech.OnInitListener listener =
        new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(final int status) {
                if (status == TextToSpeech.SUCCESS) {
                    Log.d("OnInitListener", "Text to speech engine started successfully.");
                    tts.setLanguage(Locale.US);
                } else {
                    Log.d("OnInitListener", "Error starting the text to speech engine.");
                }
            }
        };
     tts = new TextToSpeech(this.getApplicationContext(), listener);*/
}

From source file:com.busticket.amedora.busticketsrl.TicketingHomeActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.layout_ticket_home);
    myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);//from ww w . j a va  2s. co  m
    //synchTrips();
    assert getSupportActionBar() != null;
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    spBoard = (Spinner) findViewById(R.id.spBoard);
    spBuses = (Spinner) findViewById(R.id.spBusNo);
    spTrips = (Spinner) findViewById(R.id.spTripType);
    spHighlight = (Spinner) findViewById(R.id.spHighlight);
    mAccount = CreateSyncAccount(this);
    mQueue = Volley.newRequestQueue(getApplicationContext());
    rQSyncTicket = Volley.newRequestQueue(getApplicationContext());
    rQSyncTicketSynch = Volley.newRequestQueue(getApplicationContext());
    rQSyncBalance = Volley.newRequestQueue(getApplicationContext());
    rqTrip = Volley.newRequestQueue(getApplicationContext());
    rQSyncTicketing = Volley.newRequestQueue(getApplicationContext());
    rQSyncTicketingSynch = Volley.newRequestQueue(getApplicationContext());
    //Key methods needed to be sent to server on activity created
    syncTicketing();
    syncTickets();

    apps = db.getApp(Installation.appId(getApplicationContext()));
    EMAIL = apps.getRoute_name();
    NAME = "CODE: " + apps.getAgent_code().toUpperCase() + " Trip: " + apps.getTripCount();
    // Get the content resolver for your app
    mResolver = getContentResolver();
    /*
     * Turn on periodic syncing
     */

    mTitle = mDrawerTitle = getTitle();
    ContentResolver.addPeriodicSync(CreateSyncAccount(this), AUTHORITY, Bundle.EMPTY, SYNC_INTERVAL);

    String[] tdata = populateTerminals();
    String[] bdata = populateBuses();
    ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, tdata);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spBoard.setAdapter(adapter);/**/

    ArrayAdapter Hadapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, tdata);
    Hadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spHighlight.setAdapter(Hadapter);

    ArrayAdapter gadapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, bdata);
    gadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spBuses.setAdapter(gadapter);

    ArrayAdapter<CharSequence> tadapter = ArrayAdapter.createFromResource(this, R.array.tripTypes,
            android.R.layout.simple_spinner_item);
    tadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    /*ArrayAdapter badapter =new ArrayAdapter(this,android.R.layout.simple_spinner_item,bdata);
    badapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);*/
    spTrips.setAdapter(tadapter);

    spBuses.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
            //((TextView) parent.getChildAt(0)).setTextSize(25);
            bus = parent.getItemAtPosition(position).toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    spBoard.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
            //((TextView) parent.getChildAt(0)).setTextSize(25);
            board = parent.getItemAtPosition(position).toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    spHighlight.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
            //((TextView) parent.getChildAt(0)).setTextSize(25);
            highlight = parent.getItemAtPosition(position).toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    spTrips.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
            //((TextView) parent.getChildAt(0)).setTextSize(25);
            trip = parent.getItemAtPosition(position).toString();

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    btnGenerate = (Button) findViewById(R.id.btnGenerate);

    btnGenerate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // get a new activity to show invoice preview
            sendData();
        }
    });
    mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View

    mRecyclerView.setHasFixedSize(true); // Letting the system know that the list objects are of fixed size

    mAdapter = new DrawerAdapter(TITLES, ICONS, NAME, EMAIL, PROFILE); // Creating the Adapter of MyAdapter class(which we are going to see in a bit)
    // And passing the titles,icons,header view name, header view email,
    // and header view profile picture

    // Setting the adapter to RecyclerView
    //mRecyclerView.setLayoutManager(mLayoutManager);                 // Setting the layout Manager
    LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
    mRecyclerView.setLayoutManager(layoutManager);
    mRecyclerView.setAdapter(mAdapter);
    Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);
    // Drawer object Assigned to the view

    mDrawerToggle = new ActionBarDrawerToggle(this, Drawer, toolbar, R.string.openDrawer,
            R.string.closeDrawer) {
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            // code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
            // open I am not going to put anything here)
            invalidateOptionsMenu();
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            // Code here will execute once drawer is closed
            invalidateOptionsMenu();
        }
    }; // Drawer Toggle Object Made
    Drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
    mDrawerToggle.syncState(); // Finally we set the drawer toggle sync State

    final GestureDetector mGestureDetector = new GestureDetector(TicketingHomeActivity.this,
            new GestureDetector.SimpleOnGestureListener() {

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

            });

    mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
            View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
            if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
                Drawer.closeDrawers();
                if (recyclerView.getChildPosition(child) == 1) {

                } else if (recyclerView.getChildPosition(child) == 2) {
                    Intent intent = new Intent(TicketingHomeActivity.this, AccountActivity.class);
                    startActivity(intent);
                } else if (recyclerView.getChildPosition(child) == 3) {
                    Intent intent = new Intent(TicketingHomeActivity.this, TicketListActivity.class);
                    startActivity(intent);
                } else if (recyclerView.getChildPosition(child) == 4) {

                    syncTicketingSynchronize();
                    syncTicketsSynchronize();
                    synchAccount();
                    insertBuses();
                    //insertTerminals();

                    //syncTickets();

                    //dialog = ProgressDialog.show(TicketingHomeActivity.this, "", "Synchronizing App Data. Please wait...", true);
                    /*new Thread(new Runnable() {
                    @Override
                    public void run() {
                            
                        Looper.prepare();
                            
                        final Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {*/

                    // insertTerminals();

                    // insertBuses();
                    //getTickets();

                    //Toast.makeText(TicketingHomeActivity.this, "Looper startes ", Toast.LENGTH_SHORT).show();
                    /*handler.removeCallbacks(this);
                            
                    Looper.myLooper().quit();
                    }
                    }, 30000);
                            
                    Looper.loop();
                    }
                    }).start();*/

                } else if (recyclerView.getChildPosition(child) == 5) {
                    if (apps.getLicenceNo() != null) {
                        Intent intent = new Intent(TicketingHomeActivity.this, TripHomeActivity.class);
                        startActivity(intent);

                    } else {
                        //Intent intent = new Intent(TicketingHomeActivity.this,TestPrintActivity.class);
                        //startActivity(intent);
                        Toast.makeText(TicketingHomeActivity.this,
                                "Application is in default mode you cannot use this menu", Toast.LENGTH_SHORT)
                                .show();
                    }

                } else if (recyclerView.getChildPosition(child) == 6) {
                    Intent intent = new Intent(TicketingHomeActivity.this, LogoutActivity.class);
                    startActivity(intent);
                    // Toast.makeText(TicketingHomeActivity.this, "The Item Clicked is: " + recyclerView.getChildPosition(child), Toast.LENGTH_SHORT).show();
                }
                return true;
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {

        }
    });
    List<Ticket> issuedTickets = db.getIssuedTickets();
    Log.e("SYNC LOG", issuedTickets.toString());
}

From source file:com.juick.android.ThreadActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    JuickAdvancedApplication.maybeEnableAcceleration(this);
    JuickAdvancedApplication.setupTheme(this);
    //requestWindowFeature(Window.FEATURE_NO_TITLE);
    //getSherlock().requestFeature(Window.FEATURE_NO_TITLE);
    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    super.onCreate(savedInstanceState);
    handler = new Handler();

    Intent i = getIntent();/*  w  w w  . j  a v  a  2  s . c  o  m*/
    mid = (MessageID) i.getSerializableExtra("mid");
    if (mid == null) {
        finish();
    }

    messagesSource = (MessagesSource) i.getSerializableExtra("messagesSource");
    if (sp.getBoolean("fullScreenThread", false)) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
    }
    setContentView(R.layout.thread);
    /*
            findViewById(R.id.gotoMain).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        startActivity(new Intent(ThreadActivity.this, MainActivity.class));
    }
            });
    */
    final View buttons = findViewById(R.id.buttons);
    bSend = (ImageButton) findViewById(R.id.buttonSend);
    bSend.setOnClickListener(this);
    bAttach = (ImageButton) findViewById(R.id.buttonAttachment);
    bAttach.setOnClickListener(this);
    etMessage = (EditText) findViewById(R.id.editMessage);

    if (sp.getBoolean("helvNueFonts", false)) {
        etMessage.setTypeface(JuickAdvancedApplication.helvNue);
        /*
                    TextView oldTitle = (TextView)findViewById(R.id.old_title);
                    oldTitle.setTypeface(JuickAdvancedApplication.helvNue);
        */
    }

    Button cancel = (Button) findViewById(R.id.buttonCancel);
    cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            doCancel();
        }
    });

    tvReplyTo = (TextView) findViewById(R.id.textReplyTo);
    replyToContainer = (RelativeLayout) findViewById(R.id.replyToContainer);
    setHeight(replyToContainer, 0);
    showThread = (Button) findViewById(R.id.showThread);
    draftsButton = (Button) findViewById(R.id.drafts);
    etMessage.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                etMessage.setHint("");
                setHeight(buttons, ActionBar.LayoutParams.WRAP_CONTENT);
                InputMethodManager inputMgr = (InputMethodManager) getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                inputMgr.toggleSoftInput(0, 0);
            } else {
                etMessage.setHint(R.string.ClickToReply);
                setHeight(buttons, 0);
            }
            //To change body of implemented methods use File | Settings | File Templates.
        }
    });
    draftsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            class Item {
                String label;
                long ts;
                int index;

                Item(String label, long ts, int index) {
                    this.label = label;
                    this.ts = ts;
                    this.index = index;
                }
            }
            final ArrayList<Item> items = new ArrayList<Item>();
            final SharedPreferences drafts = getSharedPreferences("drafts", MODE_PRIVATE);
            for (int q = 0; q < 1000; q++) {
                String msg = drafts.getString("message" + q, null);
                if (msg != null) {
                    if (msg.length() > 50)
                        msg = msg.substring(0, 50);
                    items.add(new Item(msg, drafts.getLong("timestamp" + q, 0), q));
                }
            }
            Collections.sort(items, new Comparator<Item>() {
                @Override
                public int compare(Item item, Item item2) {
                    final long l = item2.ts - item.ts;
                    return l == 0 ? 0 : l > 0 ? 1 : -1;
                }
            });
            CharSequence[] arr = new CharSequence[items.size()];
            for (int i1 = 0; i1 < items.size(); i1++) {
                Item item = items.get(i1);
                arr[i1] = item.label;
            }
            new AlertDialog.Builder(ThreadActivity.this).setItems(arr, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, final int which) {
                    final Runnable doPull = new Runnable() {
                        @Override
                        public void run() {
                            pullDraft(null, drafts, items.get(which).index);
                            updateDraftsButton();
                        }
                    };
                    if (pulledDraft != null
                            && pulledDraft.trim().equals(etMessage.getText().toString().trim())) {
                        // no need to ask, user just looks at the drafts
                        saveDraft(pulledDraftRid, pulledDraftMid, pulledDraftTs, pulledDraft);
                        doPull.run();
                    } else {
                        if (etMessage.getText().toString().length() > 0) {
                            new AlertDialog.Builder(ThreadActivity.this)
                                    .setTitle(getString(R.string.ReplacingText))
                                    .setMessage(getString(R.string.YourTextWillBeReplaced))
                                    .setNegativeButton(android.R.string.ok,
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    doPull.run();
                                                }

                                            })
                                    .setNeutralButton(
                                            getString(pulledDraft != null ? R.string.SaveChangedDraft
                                                    : R.string.SaveDraft),
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    if (pulledDraft != null) {
                                                        saveDraft(pulledDraftRid, pulledDraftMid,
                                                                System.currentTimeMillis(),
                                                                etMessage.getText().toString());
                                                    } else {
                                                        saveDraft(rid, mid.toString(),
                                                                System.currentTimeMillis(),
                                                                etMessage.getText().toString());
                                                    }
                                                    doPull.run();
                                                }
                                            })
                                    .setPositiveButton(android.R.string.cancel,
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                }
                                            })
                                    .show();
                        } else {
                            doPull.run();
                        }
                    }
                }
            }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            }).show();
        }
    });
    enableDrafts = (sp.getBoolean("enableDrafts", false));
    if (sp.getBoolean("capitalizeReplies", false)) {
        etMessage.setInputType(etMessage.getInputType() | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES);
    }
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    tf = new ThreadFragment();
    tf.init(getLastCustomNonConfigurationInstance(), this);
    Bundle args = new Bundle();
    args.putSerializable("mid", mid);
    args.putSerializable("messagesSource", messagesSource);
    args.putSerializable("prefetched", i.getSerializableExtra("prefetched"));
    args.putSerializable("originalMessage", i.getSerializableExtra("originalMessage"));
    args.putBoolean("scrollToBottom", i.getBooleanExtra("scrollToBottom", false));
    tf.setArguments(args);
    ft.add(R.id.threadfragment, tf);
    ft.commit();
    MainActivity.restyleChildrenOrWidget(getWindow().getDecorView());
    detector = new GestureDetector(this, new GestureDetector.OnGestureListener() {
        @Override
        public boolean onDown(MotionEvent e) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {

        }

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

        @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) {
            if (velocityX > 0 && Math.abs(velocityX) > 4 * Math.abs(velocityY) && Math.abs(velocityX) > 400) {
                if (etMessage.getText().toString().trim().length() == 0) {
                    System.out.println("velocityX=" + velocityX + " velocityY" + velocityY);
                    if (sp.getBoolean("swipeToClose", true)) {
                        onBackPressed();
                    }
                }
            }
            return false;
        }
    });

    com.actionbarsherlock.app.ActionBar actionBar = getSherlock().getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setHomeButtonEnabled(true);
    actionBar.setLogo(R.drawable.back_button);

}

From source file:io.bunnyblue.noticedog.app.lockscreen.ui.LockScreenWidget.java

void setupMoveHandlers() {
    this.rootView.setOnInterceptTouchListener(new OnTouchListener() {
        GestureDetector gestureDetector = new GestureDetector(LockScreenWidget.this.context,
                new OnGestureListener() {
                    public boolean onDown(MotionEvent motionEvent) {
                        return false;
                    }/* www .  j a  v  a2s .  c  om*/

                    public void onShowPress(MotionEvent motionEvent) {
                    }

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

                    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent2, float v,
                            float v2) {
                        return false;
                    }

                    public void onLongPress(MotionEvent motionEvent) {
                    }

                    public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent2, float v,
                            float v2) {
                        if (v2 >= -1000.0f || LockScreenWidget.this.isPagerBeingDragged) {
                            return false;
                        }
                        LockScreenWidget.this.performAction(WidgetAction.actionClear);
                        return true;
                    }
                });

        public boolean onTouch(View view, MotionEvent motionEvent) {
            this.gestureDetector.onTouchEvent(motionEvent);
            boolean moved;
            switch (motionEvent.getAction()) {
            case 1:
            case 3:
                moved = false;
                if (LockScreenWidget.this.hasMoveStarted) {
                    moved = true;
                    LockScreenWidget.this.performAction(WidgetAction.actionStopMove);
                }
                LockScreenWidget.this.isTouchDown = false;
                LockScreenWidget.this.hasMoveStarted = false;
                if (moved) {
                    return true;
                }
                return false;
            case 2:
                moved = false;
                if (!LockScreenWidget.this.isTouchDown || LockScreenWidget.this.isPagerBeingDragged) {
                    return false;
                }
                if (LockScreenWidget.this.hasMoveStarted && LockScreenWidget.this.screenshotView != null) {
                    float newY = LockScreenWidget.this.screenshotView.getY()
                            + (motionEvent.getRawY() - LockScreenWidget.this.lastY);
                    int maxY = LockScreenWidget.this.fullscreenView.getHeight()
                            - LockScreenWidget.this.screenshotView.getHeight();
                    if (newY < 0.0f) {
                        Log.d(LockScreenWidget.TAG,
                                "Hit top edge with newY = " + newY + "  |   setting newY to 0");
                        newY = 0.0f;
                    } else if (newY > ((float) maxY)) {
                        Log.d(LockScreenWidget.TAG,
                                "Hit bottom edge with newY = " + newY + "  | setting newY " + maxY);
                        newY = (float) maxY;
                    }
                    LockScreenWidget.this.screenshotView.setY(newY);
                    moved = true;
                }
                LockScreenWidget.this.lastY = motionEvent.getRawY();
                if (moved) {
                    return true;
                }
                return false;
            default:
                return false;
            }
        }
    });
}

From source file:com.kll.collect.android.activities.FormEntryActivity.java

/** Called when the activity is first created. */
@Override/* ww w.  j  a v a 2  s  .  c  om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // must be at the beginning of any activity that can be called from an
    // external intent
    try {
        Collect.createODKDirs();
    } catch (RuntimeException e) {
        createErrorDialog(e.getMessage(), EXIT);
        return;
    }
    Log.i("Activity", "Created");
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mSharedPreferences
            .registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
                @Override
                public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                    compressImage = mSharedPreferences
                            .getBoolean(PreferencesActivity.KEY_ENABLE_IMAGE_COMPRESSION, false);
                }
            });
    setContentView(R.layout.form_entry);
    /*      setTitle(getString(R.string.app_name) + " > "
    + getString(R.string.loading_form));*/
    setTitle(getString(R.string.app_name));

    Log.i("Entry", "Form");
    mErrorMessage = null;
    //progressBar = (ProgressBar) findViewById(R.id.progress);
    //progressBar.setVisibility(ProgressBar.VISIBLE);
    //progressBar.setProgress(0);

    mBeenSwiped = false;
    mAlertDialog = null;
    mCurrentView = null;
    mInAnimation = null;
    mOutAnimation = null;
    mGestureDetector = new GestureDetector(this, this);
    mQuestionHolder = (LinearLayout) findViewById(R.id.questionholder);

    // get admin preference settings
    mAdminPreferences = getSharedPreferences(AdminPreferencesActivity.ADMIN_PREFERENCES, 0);

    mNextButton = (ImageButton) findViewById(R.id.form_forward_button);
    mNextButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mBeenSwiped = true;
            showNextView();
        }
    });

    mBackButton = (ImageButton) findViewById(R.id.form_back_button);
    mBackButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mBeenSwiped = true;
            showPreviousView();
        }
    });

    needLocation = mSharedPreferences.getBoolean(PreferencesActivity.KEY_GPS_FIX, false);
    if (needLocation) {

        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, this);
    }

    // Load JavaRosa modules. needed to restore forms.
    new XFormsModule().registerModule();

    // needed to override rms property manager
    org.javarosa.core.services.PropertyManager.setPropertyManager(new PropertyManager(getApplicationContext()));

    String startingXPath = null;
    String waitingXPath = null;
    String instancePath = null;
    Boolean newForm = true;
    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(KEY_FORMPATH)) {
            mFormPath = savedInstanceState.getString(KEY_FORMPATH);
        }
        if (savedInstanceState.containsKey(KEY_INSTANCEPATH)) {
            instancePath = savedInstanceState.getString(KEY_INSTANCEPATH);
        }
        if (savedInstanceState.containsKey(KEY_XPATH)) {
            startingXPath = savedInstanceState.getString(KEY_XPATH);
            Log.i(t, "startingXPath is: " + startingXPath);
        }
        if (savedInstanceState.containsKey(KEY_XPATH_WAITING_FOR_DATA)) {
            waitingXPath = savedInstanceState.getString(KEY_XPATH_WAITING_FOR_DATA);
            Log.i(t, "waitingXPath is: " + waitingXPath);
        }
        if (savedInstanceState.containsKey(NEWFORM)) {
            newForm = savedInstanceState.getBoolean(NEWFORM, true);
        }
        if (savedInstanceState.containsKey(KEY_ERROR)) {
            mErrorMessage = savedInstanceState.getString(KEY_ERROR);
        }
    }

    // If a parse error message is showing then nothing else is loaded
    // Dialogs mid form just disappear on rotation.
    if (mErrorMessage != null) {
        createErrorDialog(mErrorMessage, EXIT);
        return;
    }

    // Check to see if this is a screen flip or a new form load.
    Object data = getLastNonConfigurationInstance();
    if (data instanceof FormLoaderTask) {
        mFormLoaderTask = (FormLoaderTask) data;
    } else if (data instanceof SaveToDiskTask) {
        mSaveToDiskTask = (SaveToDiskTask) data;
    } else if (data == null) {
        if (!newForm) {
            if (Collect.getInstance().getFormController() != null) {
                refreshCurrentView();
            } else {
                Log.w(t, "Reloading form and restoring state.");
                // we need to launch the form loader to load the form
                // controller...
                mFormLoaderTask = new FormLoaderTask(instancePath, startingXPath, waitingXPath);
                Collect.getInstance().getActivityLogger().logAction(this, "formReloaded", mFormPath);
                // TODO: this doesn' work (dialog does not get removed):
                // showDialog(PROGRESS_DIALOG);
                // show dialog before we execute...
                Log.i("Loader", "Executing");
                mFormLoaderTask.execute(mFormPath);
            }
            return;
        }

        // Not a restart from a screen orientation change (or other).
        Collect.getInstance().setFormController(null);
        CompatibilityUtils.invalidateOptionsMenu(this);

        Intent intent = getIntent();
        if (intent != null) {
            Uri uri = intent.getData();

            if (getContentResolver().getType(uri).equals(InstanceColumns.CONTENT_ITEM_TYPE)) {
                // get the formId and version for this instance...
                String jrFormId = null;
                String jrVersion = null;
                {
                    Cursor instanceCursor = null;
                    try {
                        instanceCursor = getContentResolver().query(uri, null, null, null, null);
                        if (instanceCursor.getCount() != 1) {
                            this.createErrorDialog("Bad URI: " + uri, EXIT);
                            return;
                        } else {
                            instanceCursor.moveToFirst();
                            instancePath = instanceCursor.getString(
                                    instanceCursor.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
                            Collect.getInstance().getActivityLogger().logAction(this, "instanceLoaded",
                                    instancePath);

                            jrFormId = instanceCursor
                                    .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
                            int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION);

                            jrVersion = instanceCursor.isNull(idxJrVersion) ? null
                                    : instanceCursor.getString(idxJrVersion);
                        }
                    } finally {
                        if (instanceCursor != null) {
                            instanceCursor.close();
                        }
                    }
                }

                String[] selectionArgs;
                String selection;

                if (jrVersion == null) {
                    selectionArgs = new String[] { jrFormId };
                    selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + " IS NULL";
                } else {
                    selectionArgs = new String[] { jrFormId, jrVersion };
                    selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + "=?";
                }

                {
                    Cursor formCursor = null;
                    try {
                        formCursor = getContentResolver().query(FormsColumns.CONTENT_URI, null, selection,
                                selectionArgs, null);
                        if (formCursor.getCount() == 1) {
                            formCursor.moveToFirst();
                            mFormPath = formCursor
                                    .getString(formCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH));
                        } else if (formCursor.getCount() < 1) {
                            this.createErrorDialog(
                                    getString(R.string.parent_form_not_present, jrFormId)
                                            + ((jrVersion == null) ? ""
                                                    : "\n" + getString(R.string.version) + " " + jrVersion),
                                    EXIT);
                            return;
                        } else if (formCursor.getCount() > 1) {
                            // still take the first entry, but warn that
                            // there are multiple rows.
                            // user will need to hand-edit the SQLite
                            // database to fix it.
                            formCursor.moveToFirst();
                            mFormPath = formCursor
                                    .getString(formCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH));
                            this.createErrorDialog(getString(R.string.survey_multiple_forms_error), EXIT);
                            return;
                        }
                    } finally {
                        if (formCursor != null) {
                            formCursor.close();
                        }
                    }
                }
            } else if (getContentResolver().getType(uri).equals(FormsColumns.CONTENT_ITEM_TYPE)) {
                Cursor c = null;
                try {
                    c = getContentResolver().query(uri, null, null, null, null);
                    if (c.getCount() != 1) {
                        this.createErrorDialog("Bad URI: " + uri, EXIT);
                        return;
                    } else {
                        c.moveToFirst();
                        mFormPath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
                        // This is the fill-blank-form code path.
                        // See if there is a savepoint for this form that
                        // has never been
                        // explicitly saved
                        // by the user. If there is, open this savepoint
                        // (resume this filled-in
                        // form).
                        // Savepoints for forms that were explicitly saved
                        // will be recovered
                        // when that
                        // explicitly saved instance is edited via
                        // edit-saved-form.
                        final String filePrefix = mFormPath.substring(mFormPath.lastIndexOf('/') + 1,
                                mFormPath.lastIndexOf('.')) + "_";
                        final String fileSuffix = ".xml.save";
                        File cacheDir = new File(Collect.CACHE_PATH);
                        File[] files = cacheDir.listFiles(new FileFilter() {
                            @Override
                            public boolean accept(File pathname) {
                                String name = pathname.getName();
                                return name.startsWith(filePrefix) && name.endsWith(fileSuffix);
                            }
                        });
                        // see if any of these savepoints are for a
                        // filled-in form that has never been
                        // explicitly saved by the user...
                        for (int i = 0; i < files.length; ++i) {
                            File candidate = files[i];
                            String instanceDirName = candidate.getName().substring(0,
                                    candidate.getName().length() - fileSuffix.length());
                            File instanceDir = new File(
                                    Collect.INSTANCES_PATH + File.separator + instanceDirName);
                            File instanceFile = new File(instanceDir, instanceDirName + ".xml");
                            if (instanceDir.exists() && instanceDir.isDirectory() && !instanceFile.exists()) {
                                // yes! -- use this savepoint file
                                instancePath = instanceFile.getAbsolutePath();
                                break;
                            }
                        }
                    }
                } finally {
                    if (c != null) {
                        c.close();
                    }
                }
            } else {
                Log.e(t, "unrecognized URI");
                this.createErrorDialog("Unrecognized URI: " + uri, EXIT);
                return;
            }

            mFormLoaderTask = new FormLoaderTask(instancePath, null, null);
            Collect.getInstance().getActivityLogger().logAction(this, "formLoaded", mFormPath);
            showDialog(PROGRESS_DIALOG);
            // show dialog before we execute...
            Log.i("Loader", "Executing");
            mFormLoaderTask.execute(mFormPath);
        }
    }

}