Example usage for android.view View.OnTouchListener View.OnTouchListener

List of usage examples for android.view View.OnTouchListener View.OnTouchListener

Introduction

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

Prototype

View.OnTouchListener

Source Link

Usage

From source file:com.QuarkLabs.BTCeClient.fragments.HomeFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {

    mTickersContainer = (FixedGridView) getView().findViewById(R.id.tickersContainer);
    mTickersContainer.setExpanded(true);
    final int dashboardSpacing = getResources().getDimensionPixelSize(R.dimen.dashboard_spacing);
    final int dashboardItemSize = getResources().getDimensionPixelSize(R.dimen.dashboard_item_size);
    mTickersContainer.getViewTreeObserver()
            .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override//from  w  w w  . j a v  a 2 s  .  c o m
                public void onGlobalLayout() {
                    if (mTickersDashboardAdapter.getNumColumns() == 0) {
                        final int numColumns = (int) Math
                                .floor(mTickersContainer.getWidth() / (dashboardSpacing + dashboardItemSize));
                        if (numColumns > 0) {
                            mTickersDashboardAdapter.setNumColumns(numColumns);
                            mTickersContainer.setNumColumns(numColumns);
                        }
                    }
                }
            });
    mTickersDashboardAdapter = new TickersDashboardAdapter(getActivity(), this);
    updateStorageWithTickers();
    mTickersDashboardAdapter.update();
    mTickersContainer.setAdapter(mTickersDashboardAdapter);
    TextView emptyView = (TextView) getView().findViewById(R.id.emptyView);
    mTickersContainer.setEmptyView(emptyView);
    mTickersContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return event.getAction() == MotionEvent.ACTION_MOVE;
        }
    });

    //Broadcast receiver initialization
    mGetStatsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (isVisible()) {
                if (mRefreshItem != null) {
                    mRefreshItem.collapseActionView();
                    mRefreshItem.setActionView(null);
                }
                mTickersDashboardAdapter.update();
            }
        }
    };

    LocalBroadcastManager.getInstance(getActivity().getApplicationContext()).registerReceiver(mGetStatsReceiver,
            new IntentFilter("UpdateTickers"));

    //Trade listener, once "Buy" or "Sell" clicked, send the order to server
    View.OnClickListener tradeListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new RegisterTradeRequestTask().execute((v.getId() == R.id.BuyButton) ? "buy" : "sell");
        }
    };

    Button SellButton = (Button) getView().findViewById(R.id.SellButton);
    Button BuyButton = (Button) getView().findViewById(R.id.BuyButton);
    SellButton.setOnClickListener(tradeListener);
    BuyButton.setOnClickListener(tradeListener);

    Button UpdateAccountInfoButton = (Button) getView().findViewById(R.id.UpdateAccountInfoButton);

    UpdateAccountInfoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new UpdateFundsTask().execute();
        }
    });

    //start service to get new data once Dashboard is opened
    getActivity().sendBroadcast(new Intent(getActivity(), StartServiceReceiver.class));
}

From source file:org.tanrabad.team.ChatFragment.java

private void initUiComponents(View rootView) {
    mListView = (ListView) rootView.findViewById(R.id.list);
    turnOffListViewDecoration(mListView);
    mListView.setAdapter(mAdapter);/*from w w w .ja  v a  2s . c  o m*/

    mBtnChannel = (ImageButton) rootView.findViewById(R.id.btn_channel);
    mBtnSend = (Button) rootView.findViewById(R.id.btn_send);
    mBtnUpload = (ImageButton) rootView.findViewById(R.id.btn_upload);
    mProgressBtnUpload = (ProgressBar) rootView.findViewById(R.id.progress_btn_upload);
    mEtxtMessage = (EditText) rootView.findViewById(R.id.etxt_message);

    mBtnSend.setEnabled(false);
    mBtnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            send();
        }
    });

    mBtnChannel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mHandler != null) {
                mHandler.onChannelListClicked();
            }
        }
    });

    mBtnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_PICK_IMAGE);
        }
    });

    mEtxtMessage.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    send();
                }
                return true; // Do not hide keyboard.
            }
            return false;
        }
    });
    mEtxtMessage.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
    mEtxtMessage.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            mBtnSend.setEnabled(s.length() > 0);
        }
    });
    mListView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            SoftKeyboard.hide(getActivity());
            return false;
        }
    });
    mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState == SCROLL_STATE_IDLE) {
                if (view.getFirstVisiblePosition() == 0 && view.getChildCount() > 0
                        && view.getChildAt(0).getTop() == 0) {
                    resultHandler = new MessageListQuery.MessageListQueryResult() {
                        @Override
                        public void onResult(List<MessageModel> messageModels) {
                            for (MessageModel model : messageModels) {
                                mAdapter.addMessageModel(model);
                            }

                            mAdapter.notifyDataSetChanged();
                            mListView.setSelection(messageModels.size());
                        }

                        @Override
                        public void onError(Exception e) {
                        }
                    };
                    SendBird.queryMessageList(SendBird.getChannelUrl()).prev(mAdapter.getMinMessageTimestamp(),
                            30, resultHandler);
                }
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }
    });
}

From source file:org.ale.openwatch.feeds.RemoteRecordingsListFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    parentActivity = (FeedFragmentActivity) getActivity();

    // Give some text to display if there is no data.  In a real
    // application this would come from a resource.
    setEmptyText(getString(R.string.feed_empty));

    // We have a menu item to show in action bar.
    setHasOptionsMenu(true);//from   w w  w .j  a  va2  s.c om

    feed = this.getArguments().getString(Constants.OW_FEED);
    Log.i(feed.toString(), "onActivityCreated");
    // Initialize adapter without cursor. Let loader provide it when ready
    mAdapter = new OWMediaObjectAdapter(getActivity(), null);
    // Add footer loading view
    LayoutInflater layoutInflater = (LayoutInflater) parentActivity
            .getSystemService(parentActivity.LAYOUT_INFLATER_SERVICE);
    loading_footer = layoutInflater.inflate(R.layout.list_view_loading_footer,
            (ViewGroup) getActivity().findViewById(android.R.id.list), false);
    loading_footer.setVisibility(View.GONE);
    getListView().addFooterView(loading_footer);
    SharedPreferences profile = getActivity().getSharedPreferences(Constants.PROFILE_PREFS, 0);
    if (!profile.getBoolean(Constants.MISSION_TIP, false))
        addListViewHeader();
    setListAdapter(mAdapter);
    getListView().setDivider(null);
    getListView().setDividerHeight(0);

    this.getListView().setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (mPullToRefreshAttacher == null)
                attachPullToRefresh();
            return false;
        }
    });

    this.getListView().setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            if (parentActivity.videoViewListIndex != -1
                    && !(parentActivity.videoViewListIndex >= firstVisibleItem
                            && parentActivity.videoViewListIndex <= firstVisibleItem + visibleItemCount)) {
                parentActivity.removeVideoView();
            }

            if (!RemoteRecordingsListFragment.this.has_next_page)
                return;

            boolean loadMore = firstVisibleItem + visibleItemCount >= totalItemCount;

            if (loadMore) {
                RemoteRecordingsListFragment.this.fetchNextFeedPage();
            }

        }

    });

    // Start out with a progress indicator.
    setListShown(false);

    // Refresh the feed view
    if (!didRefreshFeed) {
        // If our feed demands device location and we haven't cached it
        if (Constants.isOWFeedTypeGeoSensitive(feed) && device_location == null) {
            GPSRequestCallback gps_callback = new GPSRequestCallback() {

                @Override
                public void onSuccess(Location result) {
                    device_location = result;
                    fetchNextFeedPage();
                }
            };
            DeviceLocation.getLastKnownLocation(getActivity().getApplicationContext(), false, gps_callback);
        } else {
            fetchNextFeedPage();
        }
    }
    restartLoader();

}

From source file:com.kxlapp.im.view.HorizontalListView.java

/**
 * Registers the gesture detector to receive gesture notifications for this view
 *//*from  ww w. j a v a  2s  . co  m*/
private void bindGestureDetector() {
    // Generic touch listener that can be applied to any view that needs to process gestures
    final View.OnTouchListener gestureListenerHandler = new View.OnTouchListener() {
        @Override
        public boolean onTouch(final View v, final MotionEvent event) {
            // Delegate the touch event to our gesture detector
            return mGestureDetector.onTouchEvent(event);
        }
    };

    setOnTouchListener(gestureListenerHandler);
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java

protected void setWebViewSettings(Object javascriptInterface) {
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD)
        mWebView.setOverScrollMode(View.OVER_SCROLL_IF_CONTENT_SCROLLS);
    mWebView.setScrollListener(this);
    mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);

    // Enables JS
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    // Enables and setups JS local storage
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    //@deprecated since API 19. But calling this method have simply no effect for API 19+
    webSettings.setDatabasePath(mContext.getFilesDir().getParentFile().getPath() + "/databases/");

    // Enables cross-domain calls for Ajax
    allowAjax();/*from  w  w  w.j a  v  a 2s.co  m*/

    // Fix some focus issues on old devices like HTC Wildfire
    // keyboard was not properly showed on input touch.
    mWebView.requestFocus(View.FOCUS_DOWN);
    mWebView.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!view.hasFocus()) {
                    view.requestFocus();
                }
                break;
            default:
                break;
            }

            return false;
        }
    });

    // Add JavaScript interface so JavaScript can call native functions.
    mWebView.addJavascriptInterface(javascriptInterface, "Android");
    mWebView.addJavascriptInterface(new LocalStorageJavaScriptInterface(mContext), "LocalStorage");

    WebViewClient webViewClient = new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            executeWaitingCalls();
        }
    };

    mWebView.setWebViewClient(webViewClient);
}

From source file:org.cobaltians.cobalt.fragments.CobaltFragment.java

protected void setWebViewSettings(CobaltFragment javascriptInterface) {
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD)
        mWebView.setOverScrollMode(View.OVER_SCROLL_IF_CONTENT_SCROLLS);
    mWebView.setScrollListener(this);
    mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);

    // Enables JS
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    // Enables and setups JS local storage
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    //@deprecated since API 19. But calling this method have simply no effect for API 19+
    webSettings.setDatabasePath(mContext.getFilesDir().getParentFile().getPath() + "/databases/");

    // Enables cross-domain calls for Ajax
    allowAjax();//www  .ja  v  a  2  s .  c  om

    // Fix some focus issues on old devices like HTC Wildfire
    // keyboard was not properly showed on input touch.
    mWebView.requestFocus(View.FOCUS_DOWN);
    mWebView.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!view.hasFocus()) {
                    view.requestFocus();
                }
                break;
            default:
                break;
            }

            return false;
        }
    });

    //Enable Webview debugging from chrome desktop
    if (Cobalt.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    // Add JavaScript interface so JavaScript can call native functions.
    mWebView.addJavascriptInterface(javascriptInterface, "Android");
    mWebView.addJavascriptInterface(new LocalStorageJavaScriptInterface(mContext), "LocalStorage");

    WebViewClient webViewClient = new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            executeWaitingCalls();
        }
    };

    mWebView.setWebViewClient(webViewClient);
}

From source file:net.wespot.pim.view.InqCreateInquiryFragment.java

private void setDataTime() {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMMM d, yyyy");

    String test = sdf.format(cal.getTime());
    wm_date.setText(test);/*  www.  java2s.  com*/

    sdf = new SimpleDateFormat("HH:mm");
    test = sdf.format(cal.getTime());
    wm_time.setText(test);

    wm_date.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                DialogFragment dateFrag = new DatePickerFragment();
                //                            dateFrag.show(getSupportFragmentManager(), "timePicker");
                dateFrag.show(getChildFragmentManager(), "timePicker");
                break;
            }
            return false;
        }
    });

    wm_time.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                DialogFragment timeFrag = new TimePickerFragment();
                timeFrag.show(getChildFragmentManager(), "timePicker");
                //                            timeFrag.show(getSupportFragmentManager(), "timePicker");
                break;
            }
            return false;
        }
    });
}

From source file:at.maui.cheapcast.fragment.DonationsFragment.java

/**
 * Build view for Flattr. see Flattr API for more information:
 * http://developers.flattr.net/button//*from   w ww  .ja va 2  s .  c  om*/
 */
@SuppressLint("SetJavaScriptEnabled")
@TargetApi(11)
private void buildFlattrView() {
    final FrameLayout mLoadingFrame;
    final WebView mFlattrWebview;

    mFlattrWebview = (WebView) getActivity().findViewById(R.id.donations__flattr_webview);
    mLoadingFrame = (FrameLayout) getActivity().findViewById(R.id.donations__loading_frame);

    // disable hardware acceleration for this webview to get transparent background working
    if (Build.VERSION.SDK_INT >= 11) {
        mFlattrWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // define own webview client to override loading behaviour
    mFlattrWebview.setWebViewClient(new WebViewClient() {
        /**
         * Open all links in browser, not in webview
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
            try {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString)));
            } catch (ActivityNotFoundException e) {
                openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                        getString(R.string.donations__alert_dialog_no_browser));
            }

            return false;
        }

        /**
         * Links in the flattr iframe should load in the browser not in the iframe itself,
         * http:/
         * /stackoverflow.com/questions/5641626/how-to-get-webview-iframe-link-to-launch-the
         * -browser
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            if (url.contains("flattr")) {
                HitTestResult result = view.getHitTestResult();
                if (result != null && result.getType() > 0) {
                    try {
                        view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    } catch (ActivityNotFoundException e) {
                        openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                                getString(R.string.donations__alert_dialog_no_browser));
                    }
                    view.stopLoading();
                }
            }
        }

        /**
         * After loading is done, remove frame with progress circle
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            // remove loading frame, show webview
            if (mLoadingFrame.getVisibility() == View.VISIBLE) {
                mLoadingFrame.setVisibility(View.GONE);
                mFlattrWebview.setVisibility(View.VISIBLE);
            }
        }
    });

    // get flattr values from xml config
    String projectUrl = mFlattrProjectUrl;
    String flattrUrl = this.mFlattrUrl;

    // make text white and background transparent
    String htmlStart = "<html> <head><style type='text/css'>*{color: #FFFFFF; background-color: transparent;}</style>";

    // https is not working in android 2.1 and 2.2
    String flattrScheme;
    if (Build.VERSION.SDK_INT >= 9) {
        flattrScheme = "https://";
    } else {
        flattrScheme = "http://";
    }

    // set url of flattr link
    mFlattrUrlTextView = (TextView) getActivity().findViewById(R.id.donations__flattr_url);
    mFlattrUrlTextView.setText(flattrScheme + flattrUrl);

    String flattrJavascript = "<script type='text/javascript'>" + "/* <![CDATA[ */" + "(function() {"
            + "var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];"
            + "s.type = 'text/javascript';" + "s.async = true;" + "s.src = '" + flattrScheme
            + "api.flattr.com/js/0.6/load.js?mode=auto';" + "t.parentNode.insertBefore(s, t);" + "})();"
            + "/* ]]> */" + "</script>";
    String htmlMiddle = "</head> <body> <div align='center'>";
    String flattrHtml = "<a class='FlattrButton' style='display:none;' href='" + projectUrl
            + "' target='_blank'></a> <noscript><a href='" + flattrScheme + flattrUrl
            + "' target='_blank'> <img src='" + flattrScheme
            + "api.flattr.com/button/flattr-badge-large.png' alt='Flattr this' title='Flattr this' border='0' /></a></noscript>";
    String htmlEnd = "</div> </body> </html>";

    String flattrCode = htmlStart + flattrJavascript + htmlMiddle + flattrHtml + htmlEnd;

    mFlattrWebview.getSettings().setJavaScriptEnabled(true);

    mFlattrWebview.loadData(flattrCode, "text/html", "utf-8");

    // disable scroll on touch
    mFlattrWebview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            // already handled (returns true) when moving
            return (motionEvent.getAction() == MotionEvent.ACTION_MOVE);
        }
    });

    // make background of webview transparent
    // has to be called AFTER loadData
    // http://stackoverflow.com/questions/5003156/android-webview-style-background-colortransparent-ignored-on-android-2-2
    mFlattrWebview.setBackgroundColor(0x00000000);
}

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

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

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

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

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

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

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

            if (ttsIsRunning()) {
                return false;
            }// ww w  . j  a  va2s .c  o  m

            return gestureDetector.onTouchEvent(event);
        }
    };

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

    registerForContextMenu(bookView);
    saveConfigState();

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

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

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

    updateFromPrefs();
    updateFileName(savedInstanceState, file);

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

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

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

    } else {

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

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

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

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

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

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

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

@Override
public void onCreate(Bundle savedInstanceState) {
    try {//from   w w  w .j av a 2 s .co m
        DataFramework.getInstance().open(this, Utils.packageName);
    } catch (Exception e) {
        e.printStackTrace();
    }

    super.onCreate(savedInstanceState);

    CacheData.getInstance().fillHide();

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

    OnAlarmReceiver.callAlarm(this);

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

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

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

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

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

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

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

    Utils.createDirectoriesIfIsNecessary();

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

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

    setContentView(R.layout.tweettopics_activity);

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

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

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

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

        @Override
        public void onPageScrollStateChanged(int i) {

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

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

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

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

    // cargar el popup de enlaces

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

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

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

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

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

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

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

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

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

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

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

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

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

    refreshTheme();

    reloadBarAvatar();

    refreshActionBarColumns();

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

    // comprobar si hay que proponer ir al market

    int access_count = PreferenceUtils.getApplicationAccessCount(this);

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

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

    PreferenceUtils.showChangeLog(this, true);

}