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:org.akop.ararat.view.CrosswordView.java

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

    if (!isInEditMode()) {
        setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }/*  www  . ja va 2  s .  com*/

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

    int cellFillColor = NORMAL_CELL_FILL_COLOR;
    int cheatedCellFillColor = CHEATED_CELL_FILL_COLOR;
    int mistakeCellFillColor = MISTAKE_CELL_FILL_COLOR;
    int selectedWordFillColor = SELECTED_WORD_FILL_COLOR;
    int selectedCellFillColor = SELECTED_CELL_FILL_COLOR;
    int markedCellFillColor = MARKED_CELL_FILL_COLOR;
    int numberTextColor = NUMBER_TEXT_COLOR;
    int cellStrokeColor = CELL_STROKE_COLOR;
    int circleStrokeColor = CIRCLE_STROKE_COLOR;
    int answerTextColor = ANSWER_TEXT_COLOR;

    mScaledDensity = dm.scaledDensity;
    float numberTextSize = NUMBER_TEXT_SIZE * mScaledDensity;
    mAnswerTextSize = ANSWER_TEXT_SIZE * mScaledDensity;

    mCellSize = CELL_SIZE * dm.density;
    mNumberTextPadding = NUMBER_TEXT_PADDING * dm.density;
    mIsEditable = true;
    mInputMode = INPUT_MODE_KEYBOARD;
    mSkipOccupiedOnType = false;
    mSelectFirstUnoccupiedOnNav = true;
    mMaxBitmapSize = DEFAULT_MAX_BITMAP_DIMENSION;

    // Read supplied attributes
    if (attrs != null) {
        Resources.Theme theme = context.getTheme();
        TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.CrosswordView, 0, 0);

        mCellSize = a.getDimension(R.styleable.CrosswordView_cellSize, mCellSize);
        mNumberTextPadding = a.getDimension(R.styleable.CrosswordView_numberTextPadding, mNumberTextPadding);
        numberTextSize = a.getDimension(R.styleable.CrosswordView_numberTextSize, numberTextSize);
        mAnswerTextSize = a.getDimension(R.styleable.CrosswordView_answerTextSize, mAnswerTextSize);
        answerTextColor = a.getColor(R.styleable.CrosswordView_answerTextColor, answerTextColor);
        cellFillColor = a.getColor(R.styleable.CrosswordView_defaultCellFillColor, cellFillColor);
        cheatedCellFillColor = a.getColor(R.styleable.CrosswordView_cheatedCellFillColor, cheatedCellFillColor);
        mistakeCellFillColor = a.getColor(R.styleable.CrosswordView_mistakeCellFillColor, mistakeCellFillColor);
        selectedWordFillColor = a.getColor(R.styleable.CrosswordView_selectedWordFillColor,
                selectedWordFillColor);
        selectedCellFillColor = a.getColor(R.styleable.CrosswordView_selectedCellFillColor,
                selectedCellFillColor);
        markedCellFillColor = a.getColor(R.styleable.CrosswordView_markedCellFillColor, markedCellFillColor);
        cellStrokeColor = a.getColor(R.styleable.CrosswordView_cellStrokeColor, cellStrokeColor);
        circleStrokeColor = a.getColor(R.styleable.CrosswordView_circleStrokeColor, circleStrokeColor);
        numberTextColor = a.getColor(R.styleable.CrosswordView_numberTextColor, numberTextColor);
        mIsEditable = a.getBoolean(R.styleable.CrosswordView_editable, mIsEditable);
        mSkipOccupiedOnType = a.getBoolean(R.styleable.CrosswordView_skipOccupiedOnType, mSkipOccupiedOnType);
        mSelectFirstUnoccupiedOnNav = a.getBoolean(R.styleable.CrosswordView_selectFirstUnoccupiedOnNav,
                mSelectFirstUnoccupiedOnNav);

        a.recycle();
    }

    mRevealSetsCheatFlag = true;
    mMarkerSideLength = mCellSize * MARKER_TRIANGLE_LENGTH_FRACTION;

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

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

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

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

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

    mMarkedCellFillPaint = new Paint();
    mMarkedCellFillPaint.setColor(markedCellFillColor);
    mMarkedCellFillPaint.setStyle(Paint.Style.FILL);

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

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

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

    // Compute number height
    mNumberTextPaint.getTextBounds("0", 0, "0".length(), mTempRect);
    mNumberTextHeight = mTempRect.height();

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

    mAnswerTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mAnswerTextPaint.setColor(answerTextColor);
    mAnswerTextPaint.setTextSize(mAnswerTextSize);

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

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

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

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

    mBitmapPaint = new Paint(Paint.FILTER_BITMAP_FLAG);

    mScroller = new Scroller(context, null, true);
    mZoomer = new Zoomer(context);
    mUndoBuffer = new Stack<>();

    setFocusableInTouchMode(mIsEditable && mInputMode != INPUT_MODE_NONE);
    setOnKeyListener(this);
}

From source file:com.mediatek.galleryfeature.stereo.segment.ImageShow.java

private void setupImageShow(Context context) {
    Resources res = context.getResources();
    res.getColor(R.color.background_screen);
    mGestureDetector = new GestureDetector(context, this);
    mScaleGestureDetector = new ScaleGestureDetector(context, this);
    mActivity = (Activity) context;/*w  w  w.ja  va 2 s.  c o m*/
    mEdgeEffect = new EdgeEffectCompat(context);
    mEdgeSize = res.getDimensionPixelSize(R.dimen.edge_glow_size);
}

From source file:com.vonglasow.michael.satstat.ui.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);
    float density = this.getContext().getResources().getDisplayMetrics().density;

    String versionName;/*from w  w  w  .  ja  v a 2  s.co m*/
    try {
        versionName = mainActivity.getPackageManager().getPackageInfo(mainActivity.getPackageName(),
                0).versionName;
    } catch (NameNotFoundException e) {
        versionName = "unknown";
    }

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

    mapReattach.setVisibility(View.GONE);
    isMapViewAttached = true;

    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.getMapScaleBar().setMarginVertical((int) (density * 16));
    mapMap.setBuiltInZoomControls(true);
    mapMap.getMapZoomControls().setZoomLevelMin((byte) 10);
    mapMap.getMapZoomControls().setZoomLevelMax((byte) 20);
    mapMap.getMapZoomControls().setZoomControlsOrientation(Orientation.VERTICAL_IN_OUT);
    mapMap.getMapZoomControls().setZoomInResource(R.drawable.zoom_control_in);
    mapMap.getMapZoomControls().setZoomOutResource(R.drawable.zoom_control_out);
    mapMap.getMapZoomControls().setMarginHorizontal((int) (density * 8));
    mapMap.getMapZoomControls().setMarginVertical((int) (density * 16));
    providerLocations = new HashMap<String, Location>();

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

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

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

    onlineTileSource = new OnlineTileSource(Const.TILE_SERVER_OSM, 80);
    onlineTileSource.setUserAgent(
            String.format("%s/%s (%s)", "SatStat", versionName, System.getProperty("http.agent")));
    onlineTileSource.setName(Const.TILE_CACHE_OSM).setAlpha(false).setBaseUrl(Const.TILE_URL_OSM)
            .setExtension(Const.TILE_EXTENSION_OSM).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;

    float lat = mainActivity.mSharedPreferences.getFloat(Const.KEY_PREF_MAP_LAT, 360.0f);
    float lon = mainActivity.mSharedPreferences.getFloat(Const.KEY_PREF_MAP_LON, 360.0f);

    if ((lat < 360.0f) && (lon < 360.0f)) {
        mapMap.getModel().mapViewPosition.setCenter(new LatLong(lat, lon));
    }

    int zoom = mainActivity.mSharedPreferences.getInt(Const.KEY_PREF_MAP_ZOOM, 16);
    mapMap.getModel().mapViewPosition.setZoomLevel((byte) zoom);

    createLayers(true);

    return rootView;
}

From source file:xyz.zpayh.hdimage.HDImageView.java

private void setFilingGesture(Context context) {
    mFlingDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override/*from   w w w . jav  a2 s . c om*/
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

            if (mTranslateEnabled && mReadySent && mViewTranslate != null && e1 != null && e2 != null
                    && (Math.abs(e1.getX() - e2.getX()) > 50 || Math.abs(e1.getY() - e2.getY()) > 50)
                    && (Math.abs(velocityX) > 500 || Math.abs(velocityY) > 500) && !mIsZooming) {
                PointF vTranslateEnd = new PointF(mViewTranslate.x + (velocityX * 0.25f),
                        mViewTranslate.y + (velocityY * 0.25f));
                float sCenterXEnd = ((getWidth() / 2.0F) - vTranslateEnd.x) / mScale;
                float sCenterYEnd = ((getHeight() / 2.0F) - vTranslateEnd.y) / mScale;
                startFilingAnimation(sCenterXEnd, sCenterYEnd);
                if (BuildConfig.DEBUG)
                    Log.d(TAG, "onFling: ");
                return true;
            }
            return false;
        }
    });
}

From source file:study.tdcc.act.MainCalendar.java

/**
 * ????//from   w  ww .  ja  v a2 s .co m
 *
 */
private void getViewElement() {
    Log.d("DEBUG", "MainCalendar getViewElement Start");
    //
    tvCustomTitle = (TextView) this.findViewById(R.id.titletext);
    //?
    tvCustomTitleVersion = (TextView) this.findViewById(R.id.titleversion);
    //
    vfCalendar = (ViewFlipper) this.findViewById(R.id.vfCalendar);
    //
    tvYearMonth = (TextView) findViewById(R.id.yearMonth);
    //
    gvCalendar = (GridView) findViewById(R.id.gvCalendar);
    //??
    gdObj = new GestureDetector(this, oglObj);
    Log.d("DEBUG", "MainCalendar getViewElement End");
}

From source file:com.jjoe64.graphview.Viewport.java

/**
 * creates the viewport//from   www.  j  ava  2  s . c  o  m
 *
 * @param graphView graphview
 */
Viewport(GraphView graphView) {
    mScroller = new OverScroller(graphView.getContext());
    mEdgeEffectTop = new EdgeEffectCompat(graphView.getContext());
    mEdgeEffectBottom = new EdgeEffectCompat(graphView.getContext());
    mEdgeEffectLeft = new EdgeEffectCompat(graphView.getContext());
    mEdgeEffectRight = new EdgeEffectCompat(graphView.getContext());
    mGestureDetector = new GestureDetector(graphView.getContext(), mGestureListener);
    mScaleGestureDetector = new ScaleGestureDetector(graphView.getContext(), mScaleGestureListener);

    mGraphView = graphView;
    mXAxisBoundsStatus = AxisBoundsStatus.INITIAL;
    mYAxisBoundsStatus = AxisBoundsStatus.INITIAL;
    mBackgroundColor = Color.TRANSPARENT;
    mPaint = new Paint();
}

From source file:de.tum.in.tumcampus.auxiliary.calendar.DayView.java

public DayView(Context context, CalendarController controller, ViewSwitcher viewSwitcher,
        EventLoader eventLoader, int numDays) {
    super(context);
    mContext = context;//from  w  w w .  ja  v a2 s .co m

    mResources = context.getResources();
    mNumDays = numDays;

    DATE_HEADER_FONT_SIZE = (int) mResources.getDimension(R.dimen.date_header_text_size);
    DAY_HEADER_FONT_SIZE = (int) mResources.getDimension(R.dimen.day_label_text_size);
    DAY_HEADER_HEIGHT = (int) mResources.getDimension(R.dimen.day_header_height);
    DAY_HEADER_BOTTOM_MARGIN = (int) mResources.getDimension(R.dimen.day_header_bottom_margin);
    HOURS_TEXT_SIZE = (int) mResources.getDimension(R.dimen.hours_text_size);
    AMPM_TEXT_SIZE = (int) mResources.getDimension(R.dimen.ampm_text_size);
    MIN_HOURS_WIDTH = (int) mResources.getDimension(R.dimen.min_hours_width);
    HOURS_LEFT_MARGIN = (int) mResources.getDimension(R.dimen.hours_left_margin);
    HOURS_RIGHT_MARGIN = (int) mResources.getDimension(R.dimen.hours_right_margin);
    int eventTextSizeId;
    if (mNumDays == 1) {
        eventTextSizeId = R.dimen.day_view_event_text_size;
    } else {
        eventTextSizeId = R.dimen.week_view_event_text_size;
    }
    EVENT_TEXT_FONT_SIZE = (int) mResources.getDimension(eventTextSizeId);
    MIN_EVENT_HEIGHT = mResources.getDimension(R.dimen.event_min_height);
    EVENT_TEXT_TOP_MARGIN = (int) mResources.getDimension(R.dimen.event_text_vertical_margin);
    EVENT_TEXT_BOTTOM_MARGIN = EVENT_TEXT_TOP_MARGIN;

    EVENT_TEXT_LEFT_MARGIN = (int) mResources.getDimension(R.dimen.event_text_horizontal_margin);
    EVENT_TEXT_RIGHT_MARGIN = EVENT_TEXT_LEFT_MARGIN;

    if (mScale == 0) {

        mScale = mResources.getDisplayMetrics().density;
        if (mScale != 1) {

            GRID_LINE_LEFT_MARGIN *= mScale;
            HOURS_TOP_MARGIN *= mScale;
            MIN_CELL_WIDTH_FOR_TEXT *= mScale;

            CURRENT_TIME_LINE_SIDE_BUFFER *= mScale;
            CURRENT_TIME_LINE_TOP_OFFSET *= mScale;

            MIN_Y_SPAN *= mScale;
            MAX_CELL_HEIGHT *= mScale;
            DEFAULT_CELL_HEIGHT *= mScale;
            DAY_HEADER_RIGHT_MARGIN *= mScale;
            DAY_HEADER_ONE_DAY_LEFT_MARGIN *= mScale;
            DAY_HEADER_ONE_DAY_RIGHT_MARGIN *= mScale;
            DAY_HEADER_ONE_DAY_BOTTOM_MARGIN *= mScale;
            EVENT_RECT_TOP_MARGIN *= mScale;
            EVENT_RECT_BOTTOM_MARGIN *= mScale;
            EVENT_RECT_LEFT_MARGIN *= mScale;
            EVENT_RECT_RIGHT_MARGIN *= mScale;
            EVENT_RECT_STROKE_WIDTH *= mScale;
        }
    }
    HOURS_MARGIN = HOURS_LEFT_MARGIN + HOURS_RIGHT_MARGIN;

    mCurrentTimeLine = mResources.getDrawable(R.drawable.timeline_indicator_holo_light);
    mCurrentTimeAnimateLine = mResources.getDrawable(R.drawable.timeline_indicator_activated_holo_light);
    mTodayHeaderDrawable = mResources.getDrawable(R.drawable.today_blue_week_holo_light);
    mAcceptedOrTentativeEventBoxDrawable = mResources.getDrawable(R.drawable.panel_month_event_holo_light);

    mEventLoader = eventLoader;
    mEventGeometry = new EventGeometry();
    mEventGeometry.setMinEventHeight(MIN_EVENT_HEIGHT);
    mEventGeometry.setHourGap(HOUR_GAP);
    mEventGeometry.setCellMargin(DAY_GAP);
    mController = controller;
    mViewSwitcher = viewSwitcher;
    mGestureDetector = new GestureDetector(context, new CalendarGestureListener());
    mScaleGestureDetector = new ScaleGestureDetector(getContext(), this);
    if (mCellHeight == 0) {
        mCellHeight = DEFAULT_CELL_HEIGHT;
    }
    mScroller = new OverScroller(context);
    mHScrollInterpolator = new ScrollInterpolator();
    mEdgeEffectTop = new EdgeEffectCompat(context);
    mEdgeEffectBottom = new EdgeEffectCompat(context);
    ViewConfiguration vc = ViewConfiguration.get(context);
    mScaledPagingTouchSlop = vc.getScaledPagingTouchSlop();
    mOnDownDelay = ViewConfiguration.getTapTimeout();
    OVERFLING_DISTANCE = vc.getScaledOverflingDistance();

    init(context);
}

From source file:com.google.android.apps.santatracker.rocketsleigh.RocketSleighActivity.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override// w w w.  ja v  a 2s  .co  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Log.d(LOG_TAG, "onCreate() : " + savedInstanceState);

    setContentView(R.layout.activity_jet_pack_elf);

    // App Invites
    mInvitesFragment = AppInvitesFragment.getInstance(this);

    // App Measurement
    mMeasurement = FirebaseAnalytics.getInstance(this);
    MeasurementManager.recordScreenView(mMeasurement, getString(R.string.analytics_screen_rocket));

    // [ANALYTICS SCREEN]: Rocket Sleigh
    AnalyticsManager.initializeAnalyticsTracker(this);
    AnalyticsManager.sendScreenView(R.string.analytics_screen_rocket);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        ImmersiveModeHelper.setImmersiveSticky(getWindow());
        ImmersiveModeHelper.installSystemUiVisibilityChangeListener(getWindow());
    }

    mIntroVideo = (VideoView) findViewById(R.id.intro_view);
    mIntroControl = findViewById(R.id.intro_control_view);
    if (savedInstanceState == null) {
        String path = "android.resource://" + getPackageName() + "/" + R.raw.jp_background;
        mBackgroundPlayer = new MediaPlayer();
        try {
            mBackgroundPlayer.setDataSource(this, Uri.parse(path));
            mBackgroundPlayer.setLooping(true);
            mBackgroundPlayer.prepare();
            mBackgroundPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

        boolean nomovie = false;
        if (getIntent().getBooleanExtra("nomovie", false)) {
            nomovie = true;
        } else if (Build.MANUFACTURER.toUpperCase().contains("SAMSUNG")) {
            //                nomovie = true;
        }
        if (!nomovie) {
            mIntroControl.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    endIntro();
                }
            });
            path = "android.resource://" + getPackageName() + "/" + R.raw.intro_wipe;
            mIntroVideo.setVideoURI(Uri.parse(path));
            mIntroVideo.setOnCompletionListener(this);
            mIntroVideo.start();
            mMoviePlaying = true;
        } else {
            mIntroControl.setOnClickListener(null);
            mIntroControl.setVisibility(View.GONE);
            mIntroVideo.setVisibility(View.GONE);
        }
    } else {
        mIntroControl.setOnClickListener(null);
        mIntroControl.setVisibility(View.GONE);
        mIntroVideo.setVisibility(View.GONE);
    }

    mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // For hit indication.

    mHandler = new Handler(); // Get the main UI handler for posting update events

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);

    Log.d(LOG_TAG, "Width: " + dm.widthPixels + " Height: " + dm.heightPixels + " Density: " + dm.density);

    mScreenHeight = dm.heightPixels;
    mScreenWidth = dm.widthPixels;
    mSlotWidth = mScreenWidth / SLOTS_PER_SCREEN;

    // Setup the random number generator
    mRandom = new Random();
    mRandom.setSeed(System.currentTimeMillis()); // This is ok.  We are not looking for cryptographically secure random here!

    mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    // Setup the background/foreground
    mBackgroundLayout = (LinearLayout) findViewById(R.id.background_layout);
    mBackgroundScroll = (HorizontalScrollView) findViewById(R.id.background_scroll);
    mForegroundLayout = (LinearLayout) findViewById(R.id.foreground_layout);
    mForegroundScroll = (HorizontalScrollView) findViewById(R.id.foreground_scroll);

    mBackgrounds = new Bitmap[6];
    mBackgrounds2 = new Bitmap[6];
    mExitTransitions = new Bitmap[6];
    mEntryTransitions = new Bitmap[6];

    // Need to vertically scale background to fit the screen.  Checkthe image size
    // compared to screen size and scale appropriately.  We will also use the matrix to translate
    // as we move through the level.
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), BACKGROUNDS[0]);
    Log.d(LOG_TAG, "Bitmap Width: " + bmp.getWidth() + " Height: " + bmp.getHeight() + " Screen Width: "
            + dm.widthPixels + " Height: " + dm.heightPixels);
    mScaleY = (float) dm.heightPixels / (float) bmp.getHeight();
    mScaleX = (float) (dm.widthPixels * 2) / (float) bmp.getWidth(); // Ensure that a single bitmap is 2 screens worth of time.  (Stock xxhdpi image is 3840x1080)

    if ((mScaleX != 1.0f) || (mScaleY != 1.0f)) {
        Bitmap tmp = Bitmap.createScaledBitmap(bmp, mScreenWidth * 2, mScreenHeight, false);
        if (tmp != bmp) {
            bmp.recycle();
            bmp = tmp;
        }
    }
    BackgroundLoadTask.createTwoBitmaps(bmp, mBackgrounds, mBackgrounds2, 0);

    // Load the initial background view
    addNextImages(0);
    addNextImages(0);

    mWoodObstacles = new TreeMap<Integer, Bitmap>();
    mWoodObstacleList = new ArrayList<Integer>();
    mWoodObstacleIndex = 0;
    // We need the bitmaps, so we do pre-load here synchronously.
    initObstaclesAndPreLoad(WOOD_OBSTACLES, 3, mWoodObstacles, mWoodObstacleList);

    mCaveObstacles = new TreeMap<Integer, Bitmap>();
    mCaveObstacleList = new ArrayList<Integer>();
    mCaveObstacleIndex = 0;
    initObstacles(CAVE_OBSTACLES, 2, mCaveObstacleList);

    mFactoryObstacles = new TreeMap<Integer, Bitmap>();
    mFactoryObstacleList = new ArrayList<Integer>();
    mFactoryObstacleIndex = 0;
    initObstacles(FACTORY_OBSTACLES, 2, mFactoryObstacleList);

    // Setup the elf
    mElf = (ImageView) findViewById(R.id.elf_image);
    mThrust = (ImageView) findViewById(R.id.thrust_image);
    mElfLayout = (LinearLayout) findViewById(R.id.elf_container);
    loadElfImages();
    updateElf(false);
    // Elf should be the same height relative to the height of the screen on any platform.
    Matrix scaleMatrix = new Matrix();
    mElfScale = ((float) dm.heightPixels * 0.123f) / (float) mElfBitmap.getHeight(); // On a 1920x1080 xxhdpi screen, this makes the elf 133 pixels which is the height of the drawable.
    scaleMatrix.preScale(mElfScale, mElfScale);
    mElf.setImageMatrix(scaleMatrix);
    mThrust.setImageMatrix(scaleMatrix);
    mElfPosX = (dm.widthPixels * 15) / 100; // 15% Into the screen
    mElfPosY = (dm.heightPixels - ((float) mElfBitmap.getHeight() * mElfScale)) / 2; // About 1/2 way down.
    mElfVelX = (float) dm.widthPixels / 3000.0f; // We start at 3 seconds for a full screen to scroll.
    mGravityAccelY = (float) (2 * dm.heightPixels) / (float) Math.pow((1.2 * 1000.0), 2.0); // a = 2*d/t^2 Where d = height in pixels and t = 1.2 seconds
    mThrustAccelY = (float) (2 * dm.heightPixels) / (float) Math.pow((0.7 * 1000.0), 2.0); // a = 2*d/t^2 Where d = height in pixels and t = 0.7 seconds

    // Setup the control view
    mControlView = findViewById(R.id.control_view);
    mGestureDetector = new GestureDetector(this, this);
    mGestureDetector.setIsLongpressEnabled(true);
    mGestureDetector.setOnDoubleTapListener(this);

    mScoreLabel = getString(R.string.score);
    mScoreText = (TextView) findViewById(R.id.score_text);
    mScoreText.setText("0");

    mPlayPauseButton = (ImageView) findViewById(R.id.play_pause_button);
    mExit = (ImageView) findViewById(R.id.exit);

    // Is Tv?
    mIsTv = TvUtil.isTv(this);
    if (mIsTv) {
        mScoreText.setText(mScoreLabel + ": 0");
        mPlayPauseButton.setVisibility(View.GONE);
        mExit.setVisibility(View.GONE);
        // move scoreLayout position to the Top-Right corner.
        View scoreLayout = findViewById(R.id.score_layout);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) scoreLayout.getLayoutParams();
        params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        params.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

        final int marginTop = getResources().getDimensionPixelOffset(R.dimen.overscan_margin_top);
        final int marginLeft = getResources().getDimensionPixelOffset(R.dimen.overscan_margin_left);

        params.setMargins(marginLeft, marginTop, 0, 0);
        scoreLayout.setLayoutParams(params);
        scoreLayout.setBackground(null);
        scoreLayout.findViewById(R.id.score_text_seperator).setVisibility(View.GONE);
    } else {
        mPlayPauseButton.setEnabled(false);
        mPlayPauseButton.setOnClickListener(this);
        mExit.setOnClickListener(this);
    }

    mBigPlayButtonLayout = findViewById(R.id.big_play_button_layout);
    mBigPlayButtonLayout.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // No interaction with the screen below this one.
            return true;
        }
    });
    mBigPlayButton = (ImageButton) findViewById(R.id.big_play_button);
    mBigPlayButton.setOnClickListener(this);

    // For showing points when getting presents.
    mPlus100 = (ImageView) findViewById(R.id.plus_100);
    m100Anim = new AlphaAnimation(1.0f, 0.0f);
    m100Anim.setDuration(1000);
    m100Anim.setFillBefore(true);
    m100Anim.setFillAfter(true);
    mPlus500 = (ImageView) findViewById(R.id.plus_500);
    m500Anim = new AlphaAnimation(1.0f, 0.0f);
    m500Anim.setDuration(1000);
    m500Anim.setFillBefore(true);
    m500Anim.setFillAfter(true);

    // Get the obstacle layouts ready.  No obstacles on the first screen of a level.
    // Prime with a screen full of obstacles.
    mObstacleLayout = (LinearLayout) findViewById(R.id.obstacles_layout);
    mObstacleScroll = (HorizontalScrollView) findViewById(R.id.obstacles_scroll);

    // Initialize the present bitmaps.  These are used repeatedly so we keep them loaded.
    mGiftBoxes = new Bitmap[GIFT_BOXES.length];
    for (int i = 0; i < GIFT_BOXES.length; i++) {
        mGiftBoxes[i] = BitmapFactory.decodeResource(getResources(), GIFT_BOXES[i]);
    }

    // Add starting obstacles.  First screen has presents.  Next 3 get obstacles.
    addFirstScreenPresents();
    //        addFinalPresentRun();  // This adds 2 screens of presents
    //        addNextObstacles(0, 1);
    addNextObstacles(0, 3);

    // Setup the sound pool
    mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
    mSoundPool.setOnLoadCompleteListener(this);
    mCrashSound1 = mSoundPool.load(this, R.raw.jp_crash_1, 1);
    mCrashSound2 = mSoundPool.load(this, R.raw.jp_crash_2, 1);
    mCrashSound3 = mSoundPool.load(this, R.raw.jp_crash_3, 1);
    mGameOverSound = mSoundPool.load(this, R.raw.jp_game_over, 1);
    mJetThrustSound = mSoundPool.load(this, R.raw.jp_jet_thrust, 1);
    mLevelUpSound = mSoundPool.load(this, R.raw.jp_level_up, 1);
    mScoreBigSound = mSoundPool.load(this, R.raw.jp_score_big, 1);
    mScoreSmallSound = mSoundPool.load(this, R.raw.jp_score_small, 1);
    mJetThrustStream = 0;

    if (!mMoviePlaying) {
        doCountdown();
    }
}

From source file:net.nanocosmos.bintu.demo.encoder.activities.StreamActivity.java

private void initStreamLib() {
    if (null == streamLib) {
        try {/*from  www. ja v a 2  s .c om*/
            nanoStreamSettings nss = configureNanostreamSettings();
            streamLib = new nanoStream(nss);
            usedVideoResolution = new Resolution(streamLib.getVideoSourceFormat().getWidth(),
                    streamLib.getVideoSourceFormat().getHeight());
        } catch (NanostreamException en) {
            Toast.makeText(getApplicationContext(), en.toString(), Toast.LENGTH_LONG).show();
        }

        if (null != streamLib) {

            try {
                streamLib.init();
            } catch (NanostreamException e) {
                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }

            // set the Device properties collected at the first time app was started in BintuApplication.java
            // this is necessary for pre Android 4.3 Devices, because this Devices may show some color format issues.
            // this will correct these color issues.
            // for mor information http://www.nanocosmos.de/v4/documentation/android_device_properties
            streamLib.setDeviceProperties(BintuApplication.getDeviceProperties());

            // initial check if the device is in portrait mode (default is landscape Rotation.ROTATION_0)
            if (getResources().getConfiguration().orientation == getResources()
                    .getConfiguration().ORIENTATION_PORTRAIT) {
                prevRotation = Rotation.ROTATION_90;
                streamRotation = Rotation.ROTATION_90;
                streamLib.setPreviewRotation(prevRotation);
                streamLib.setStreamRotation(streamRotation);
            }

            if (streamVideo) {
                mZoomRatios = streamLib.getZoomRatios();
                streamLib.addFocusCalback(this);
            }

            if (ENABLE_AUDIO_LEVEL_CALLBACK) {
                streamLib.addAudioLevelCallback(this);
            }
        }
        // the scaleGestureDetector is needed for pinch to zoom.
        if (null == scaleGestureDetector) {
            scaleGestureDetector = new ScaleGestureDetector(this, new ScaleGestureListener());
        }

        // the gestureDetector is needed for tap to focus and long press to focus lock
        if (null == gestureDetector) {
            gestureDetector = new GestureDetector(this, new GestureListener());
        }
    }
}