Example usage for android.content Context getTheme

List of usage examples for android.content Context getTheme

Introduction

In this page you can find the example usage for android.content Context getTheme.

Prototype

@ViewDebug.ExportedProperty(deepExport = true)
public abstract Resources.Theme getTheme();

Source Link

Document

Return the Theme object associated with this Context.

Usage

From source file:com.alimuzaffar.lib.widgets.PinEntryEditText.java

private void init(Context context, AttributeSet attrs) {
    float multi = context.getResources().getDisplayMetrics().density;
    mLineStroke = multi * mLineStroke;/*from   w  w  w. j a  v  a 2 s  . c  o m*/
    mLineStrokeSelected = multi * mLineStrokeSelected;
    mSpace = multi * mSpace; //convert to pixels for our density
    mTextBottomPadding = multi * mTextBottomPadding; //convert to pixels for our density

    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.PinEntryEditText, 0, 0);
    try {
        TypedValue outValue = new TypedValue();
        ta.getValue(R.styleable.PinEntryEditText_pinAnimationType, outValue);
        mAnimatedType = outValue.data;
        mMask = ta.getString(R.styleable.PinEntryEditText_pinCharacterMask);
        mLineStroke = ta.getDimension(R.styleable.PinEntryEditText_pinLineStroke, mLineStroke);
        mLineStrokeSelected = ta.getDimension(R.styleable.PinEntryEditText_pinLineStrokeSelected,
                mLineStrokeSelected);
        mSpace = ta.getDimension(R.styleable.PinEntryEditText_pinCharacterSpacing, mSpace);
        mTextBottomPadding = ta.getDimension(R.styleable.PinEntryEditText_pinTextBottomPadding,
                mTextBottomPadding);
        mIsDigitSquare = ta.getBoolean(R.styleable.PinEntryEditText_pinBackgroundIsSquare, mIsDigitSquare);
        mPinBackground = ta.getDrawable(R.styleable.PinEntryEditText_pinBackgroundDrawable);
        ColorStateList colors = ta.getColorStateList(R.styleable.PinEntryEditText_pinLineColors);
        if (colors != null) {
            mColorStates = colors;
        }
    } finally {
        ta.recycle();
    }

    mCharPaint = new Paint(getPaint());
    mLastCharPaint = new Paint(getPaint());
    mLinesPaint = new Paint(getPaint());
    mLinesPaint.setStrokeWidth(mLineStroke);

    TypedValue outValue = new TypedValue();
    context.getTheme().resolveAttribute(R.attr.colorControlActivated, outValue, true);
    int colorSelected = outValue.data;
    mColors[0] = colorSelected;

    int colorFocused = isInEditMode() ? Color.GRAY : ContextCompat.getColor(context, R.color.pin_normal);
    mColors[1] = colorFocused;

    int colorUnfocused = isInEditMode() ? Color.GRAY : ContextCompat.getColor(context, R.color.pin_normal);
    mColors[2] = colorUnfocused;

    setBackgroundResource(0);

    mMaxLength = attrs.getAttributeIntValue(XML_NAMESPACE_ANDROID, "maxLength", 4);
    mNumChars = mMaxLength;

    //Disable copy paste
    super.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public void onDestroyActionMode(ActionMode mode) {
        }

        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            return false;
        }
    });
    // When tapped, move cursor to end of text.
    super.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            setSelection(getText().length());
            if (mClickListener != null) {
                mClickListener.onClick(v);
            }
        }
    });

    super.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            setSelection(getText().length());
            return true;
        }
    });

    //If input type is password and no mask is set, use a default mask
    if ((getInputType() & InputType.TYPE_TEXT_VARIATION_PASSWORD) == InputType.TYPE_TEXT_VARIATION_PASSWORD
            && TextUtils.isEmpty(mMask)) {
        mMask = "\u25CF";
    } else if ((getInputType()
            & InputType.TYPE_NUMBER_VARIATION_PASSWORD) == InputType.TYPE_NUMBER_VARIATION_PASSWORD
            && TextUtils.isEmpty(mMask)) {
        mMask = "\u25CF";
    }

    if (!TextUtils.isEmpty(mMask)) {
        mMaskChars = getMaskChars();
    }

    //Height of the characters, used if there is a background drawable
    getPaint().getTextBounds("|", 0, 1, mTextHeight);
}

From source file:android.support.v7ox.app.AppCompatDelegateImplV7.java

@Override
ActionMode startSupportActionModeFromWindow(ActionMode.Callback callback) {
    endOnGoingFadeAnimation();/*w w  w  .j  av a  2  s . c o m*/
    if (mActionMode != null) {
        mActionMode.finish();
    }

    final ActionMode.Callback wrappedCallback = new ActionModeCallbackWrapperV7(callback);
    ActionMode mode = null;
    if (mAppCompatCallback != null && !isDestroyed()) {
        try {
            mode = mAppCompatCallback.onWindowStartingSupportActionMode(wrappedCallback);
        } catch (AbstractMethodError ame) {
            // Older apps might not implement this callback method.
        }
    }

    if (mode != null) {
        mActionMode = mode;
    } else {
        if (mActionModeView == null) {
            if (mIsFloating) {
                // Use the action bar theme.
                final TypedValue outValue = new TypedValue();
                final Resources.Theme baseTheme = mContext.getTheme();
                baseTheme.resolveAttribute(R.attr.actionBarTheme_ox, outValue, true);

                final Context actionBarContext;
                if (outValue.resourceId != 0) {
                    final Resources.Theme actionBarTheme = mContext.getResources().newTheme();
                    actionBarTheme.setTo(baseTheme);
                    actionBarTheme.applyStyle(outValue.resourceId, true);

                    actionBarContext = new ContextThemeWrapper(mContext, 0);
                    actionBarContext.getTheme().setTo(actionBarTheme);
                } else {
                    actionBarContext = mContext;
                }

                mActionModeView = new ActionBarContextView(actionBarContext);
                mActionModePopup = new PopupWindow(actionBarContext, null,
                        R.attr.actionModePopupWindowStyle_ox);
                PopupWindowCompat.setWindowLayoutType(mActionModePopup,
                        WindowManager.LayoutParams.TYPE_APPLICATION);
                mActionModePopup.setContentView(mActionModeView);
                mActionModePopup.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);

                actionBarContext.getTheme().resolveAttribute(R.attr.actionBarSize_ox, outValue, true);
                final int height = TypedValue.complexToDimensionPixelSize(outValue.data,
                        actionBarContext.getResources().getDisplayMetrics());
                mActionModeView.setContentHeight(height);
                mActionModePopup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                mShowActionModePopup = new Runnable() {
                    public void run() {
                        mActionModePopup.showAtLocation(mActionModeView, Gravity.TOP | Gravity.FILL_HORIZONTAL,
                                0, 0);
                        endOnGoingFadeAnimation();
                        ViewCompat.setAlpha(mActionModeView, 0f);
                        mFadeAnim = ViewCompat.animate(mActionModeView).alpha(1f);
                        mFadeAnim.setListener(new ViewPropertyAnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(View view) {
                                ViewCompat.setAlpha(mActionModeView, 1f);
                                mFadeAnim.setListener(null);
                                mFadeAnim = null;
                            }

                            @Override
                            public void onAnimationStart(View view) {
                                mActionModeView.setVisibility(View.VISIBLE);
                            }
                        });
                    }
                };
            } else {
                ViewStubCompat stub = (ViewStubCompat) mSubDecor.findViewById(R.id.action_mode_bar_stub);
                if (stub != null) {
                    // Set the layout inflater so that it is inflated with the action bar's context
                    stub.setLayoutInflater(LayoutInflater.from(getActionBarThemedContext()));
                    mActionModeView = (ActionBarContextView) stub.inflate();
                }
            }
        }

        if (mActionModeView != null) {
            endOnGoingFadeAnimation();
            mActionModeView.killMode();
            mode = new StandaloneActionMode(mActionModeView.getContext(), mActionModeView, wrappedCallback,
                    mActionModePopup == null);
            if (callback.onCreateActionMode(mode, mode.getMenu())) {
                mode.invalidate();
                mActionModeView.initForMode(mode);
                mActionMode = mode;
                ViewCompat.setAlpha(mActionModeView, 0f);
                mFadeAnim = ViewCompat.animate(mActionModeView).alpha(1f);
                mFadeAnim.setListener(new ViewPropertyAnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(View view) {
                        ViewCompat.setAlpha(mActionModeView, 1f);
                        mFadeAnim.setListener(null);
                        mFadeAnim = null;
                    }

                    @Override
                    public void onAnimationStart(View view) {
                        mActionModeView.setVisibility(View.VISIBLE);
                        mActionModeView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
                        if (mActionModeView.getParent() != null) {
                            ViewCompat.requestApplyInsets((View) mActionModeView.getParent());
                        }
                    }
                });
                if (mActionModePopup != null) {
                    mWindow.getDecorView().post(mShowActionModePopup);
                }
            } else {
                mActionMode = null;
            }
        }
    }
    if (mActionMode != null && mAppCompatCallback != null) {
        mAppCompatCallback.onSupportActionModeStarted(mActionMode);
    }
    return mActionMode;
}

From source file:com.android.settings.security.SecurityFeatureProviderImpl.java

@VisibleForTesting
void updatePreferencesToRunOnWorkerThread(Context context, PreferenceScreen preferenceScreen,
        DashboardCategory dashboardCategory) {

    int tilesCount = (dashboardCategory != null) ? dashboardCategory.getTilesCount() : 0;
    Map<String, IContentProvider> providerMap = new ArrayMap<>();
    for (int i = 0; i < tilesCount; i++) {
        Tile tile = dashboardCategory.getTile(i);
        // If the tile does not have a key or appropriate meta data, skip it.
        if (TextUtils.isEmpty(tile.key) || (tile.metaData == null)) {
            continue;
        }//from   w  ww  .  ja v  a 2  s  .  c om
        Preference matchingPref = preferenceScreen.findPreference(tile.key);
        // If the tile does not have a matching preference, skip it.
        if (matchingPref == null) {
            continue;
        }
        // Check if the tile has content providers for dynamically updatable content.
        final String iconUri = tile.metaData.getString(TileUtils.META_DATA_PREFERENCE_ICON_URI, null);
        final String summaryUri = tile.metaData.getString(TileUtils.META_DATA_PREFERENCE_SUMMARY_URI, null);
        if (!TextUtils.isEmpty(iconUri)) {
            String packageName = null;
            if (tile.intent != null) {
                Intent intent = tile.intent;
                if (!TextUtils.isEmpty(intent.getPackage())) {
                    packageName = intent.getPackage();
                } else if (intent.getComponent() != null) {
                    packageName = intent.getComponent().getPackageName();
                }
            }
            Pair<String, Integer> icon = TileUtils.getIconFromUri(context, packageName, iconUri, providerMap);
            if (icon != null) {
                sIconCache.put(iconUri, icon);
                // Icon is only returned if the icon belongs to Settings or the target app.
                // setIcon must be called on the UI thread.
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            matchingPref.setIcon(context.getPackageManager()
                                    .getResourcesForApplication(icon.first /* package name */)
                                    .getDrawable(icon.second /* res id */, context.getTheme()));
                        } catch (PackageManager.NameNotFoundException | Resources.NotFoundException e) {
                            // Intentionally ignored. If icon resources cannot be found, do not
                            // update.
                        }
                    }
                });
            }
        }
        if (!TextUtils.isEmpty(summaryUri)) {
            String summary = TileUtils.getTextFromUri(context, summaryUri, providerMap,
                    TileUtils.META_DATA_PREFERENCE_SUMMARY);
            sSummaryCache.put(summaryUri, summary);
            // setSummary must be called on UI thread.
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    // Only update the summary if it has actually changed.
                    if (summary == null) {
                        if (matchingPref.getSummary() != null) {
                            matchingPref.setSummary(summary);
                        }
                    } else if (!summary.equals(matchingPref.getSummary())) {
                        matchingPref.setSummary(summary);
                    }
                }
            });
        }
    }
}

From source file:com.alimuzaffar.lib.pin.PinEntryEditText.java

private void init(Context context, AttributeSet attrs) {
    float multi = context.getResources().getDisplayMetrics().density;
    mLineStroke = multi * mLineStroke;/*from   w  w w .j  a  v  a2s  .c o  m*/
    mLineStrokeSelected = multi * mLineStrokeSelected;
    mSpace = multi * mSpace; //convert to pixels for our density
    mTextBottomPadding = multi * mTextBottomPadding; //convert to pixels for our density

    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.PinEntryEditText, 0, 0);
    try {
        TypedValue outValue = new TypedValue();
        ta.getValue(R.styleable.PinEntryEditText_pinAnimationType, outValue);
        mAnimatedType = outValue.data;
        mMask = ta.getString(R.styleable.PinEntryEditText_pinCharacterMask);
        mSingleCharHint = ta.getString(R.styleable.PinEntryEditText_pinRepeatedHint);
        mLineStroke = ta.getDimension(R.styleable.PinEntryEditText_pinLineStroke, mLineStroke);
        mLineStrokeSelected = ta.getDimension(R.styleable.PinEntryEditText_pinLineStrokeSelected,
                mLineStrokeSelected);
        mSpace = ta.getDimension(R.styleable.PinEntryEditText_pinCharacterSpacing, mSpace);
        mTextBottomPadding = ta.getDimension(R.styleable.PinEntryEditText_pinTextBottomPadding,
                mTextBottomPadding);
        mIsDigitSquare = ta.getBoolean(R.styleable.PinEntryEditText_pinBackgroundIsSquare, mIsDigitSquare);
        mPinBackground = ta.getDrawable(R.styleable.PinEntryEditText_pinBackgroundDrawable);
        ColorStateList colors = ta.getColorStateList(R.styleable.PinEntryEditText_pinLineColors);
        if (colors != null) {
            mColorStates = colors;
        }
    } finally {
        ta.recycle();
    }

    mCharPaint = new Paint(getPaint());
    mLastCharPaint = new Paint(getPaint());
    mSingleCharPaint = new Paint(getPaint());
    mLinesPaint = new Paint(getPaint());
    mLinesPaint.setStrokeWidth(mLineStroke);

    TypedValue outValue = new TypedValue();
    context.getTheme().resolveAttribute(R.attr.colorControlActivated, outValue, true);
    int colorSelected = outValue.data;
    mColors[0] = colorSelected;

    int colorFocused = isInEditMode() ? Color.GRAY : ContextCompat.getColor(context, R.color.pin_normal);
    mColors[1] = colorFocused;

    int colorUnfocused = isInEditMode() ? Color.GRAY : ContextCompat.getColor(context, R.color.pin_normal);
    mColors[2] = colorUnfocused;

    setBackgroundResource(0);

    mMaxLength = attrs.getAttributeIntValue(XML_NAMESPACE_ANDROID, "maxLength", 4);
    mNumChars = mMaxLength;

    //Disable copy paste
    super.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public void onDestroyActionMode(ActionMode mode) {
        }

        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            return false;
        }
    });
    // When tapped, move cursor to end of text.
    super.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            setSelection(getText().length());
            if (mClickListener != null) {
                mClickListener.onClick(v);
            }
        }
    });

    super.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            setSelection(getText().length());
            return true;
        }
    });

    //If input type is password and no mask is set, use a default mask
    if ((getInputType() & InputType.TYPE_TEXT_VARIATION_PASSWORD) == InputType.TYPE_TEXT_VARIATION_PASSWORD
            && TextUtils.isEmpty(mMask)) {
        mMask = "\u25CF";
    } else if ((getInputType()
            & InputType.TYPE_NUMBER_VARIATION_PASSWORD) == InputType.TYPE_NUMBER_VARIATION_PASSWORD
            && TextUtils.isEmpty(mMask)) {
        mMask = "\u25CF";
    }

    if (!TextUtils.isEmpty(mMask)) {
        mMaskChars = getMaskChars();
    }

    //Height of the characters, used if there is a background drawable
    getPaint().getTextBounds("|", 0, 1, mTextHeight);

    mAnimate = mAnimatedType > -1;
}

From source file:com.grottworkshop.gwsmaterialcalendarview.MaterialCalendarView.java

@SuppressWarnings("deprecation")
public MaterialCalendarView(Context context, AttributeSet attrs) {
    super(context, attrs);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        //If we're on good Android versions, turn off clipping for cool effects
        setClipToPadding(false);/*from w w  w.j  a v a2  s  . com*/
        setClipChildren(false);
    } else {
        //Old Android does not like _not_ clipping view pagers, we need to clip
        setClipChildren(true);
        setClipToPadding(true);
    }

    buttonPast = new DirectionButton(getContext());
    title = new TextView(getContext());
    buttonFuture = new DirectionButton(getContext());
    pager = new ViewPager(getContext());

    setupChildren();

    title.setOnClickListener(onClickListener);
    buttonPast.setOnClickListener(onClickListener);
    buttonFuture.setOnClickListener(onClickListener);

    titleChanger = new TitleChanger(title);
    titleChanger.setTitleFormatter(DEFAULT_TITLE_FORMATTER);
    adapter = new MonthPagerAdapter();
    adapter.setTitleFormatter(DEFAULT_TITLE_FORMATTER);
    pager.setAdapter(adapter);
    pager.setOnPageChangeListener(pageChangeListener);
    pager.setPageTransformer(false, new ViewPager.PageTransformer() {
        @Override
        public void transformPage(View page, float position) {
            position = (float) Math.sqrt(1 - Math.abs(position));
            page.setAlpha(position);
        }
    });

    adapter.setCallbacks(monthViewCallbacks);

    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MaterialCalendarView, 0, 0);
    try {

        int tileSize = a.getDimensionPixelSize(R.styleable.MaterialCalendarView_mcv_tileSize, -1);
        if (tileSize > 0) {
            setTileSize(tileSize);
        }

        setArrowColor(a.getColor(R.styleable.MaterialCalendarView_mcv_arrowColor, Color.BLACK));
        Drawable leftMask = a.getDrawable(R.styleable.MaterialCalendarView_mcv_leftArrowMask);
        if (leftMask == null) {
            //TODO: getDrawable depreciated
            leftMask = getResources().getDrawable(R.drawable.mcv_action_previous);
        }
        setLeftArrowMask(leftMask);
        Drawable rightMask = a.getDrawable(R.styleable.MaterialCalendarView_mcv_rightArrowMask);
        if (rightMask == null) {
            //TODO: getDrawable depreciated
            rightMask = getResources().getDrawable(R.drawable.mcv_action_next);
        }
        setRightArrowMask(rightMask);

        setSelectionColor(
                a.getColor(R.styleable.MaterialCalendarView_mcv_selectionColor, getThemeAccentColor(context)));

        CharSequence[] array = a.getTextArray(R.styleable.MaterialCalendarView_mcv_weekDayLabels);
        if (array != null) {
            setWeekDayFormatter(new ArrayWeekDayFormatter(array));
        }

        array = a.getTextArray(R.styleable.MaterialCalendarView_mcv_monthLabels);
        if (array != null) {
            setTitleFormatter(new MonthArrayTitleFormatter(array));
        }

        setHeaderTextAppearance(a.getResourceId(R.styleable.MaterialCalendarView_mcv_headerTextAppearance,
                R.style.TextAppearance_MaterialCalendarWidget_Header));
        setWeekDayTextAppearance(a.getResourceId(R.styleable.MaterialCalendarView_mcv_weekDayTextAppearance,
                R.style.TextAppearance_MaterialCalendarWidget_WeekDay));
        setDateTextAppearance(a.getResourceId(R.styleable.MaterialCalendarView_mcv_dateTextAppearance,
                R.style.TextAppearance_MaterialCalendarWidget_Date));
        setShowOtherDates(a.getBoolean(R.styleable.MaterialCalendarView_mcv_showOtherDates, false));

        int firstDayOfWeek = a.getInt(R.styleable.MaterialCalendarView_mcv_firstDayOfWeek, -1);
        if (firstDayOfWeek < 0) {
            firstDayOfWeek = CalendarUtils.getInstance().getFirstDayOfWeek();
        }
        setFirstDayOfWeek(firstDayOfWeek);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        a.recycle();
    }

    currentMonth = CalendarDay.today();
    setCurrentDate(currentMonth);

    if (isInEditMode()) {
        removeView(pager);
        MonthView monthView = new MonthView(context, currentMonth, getFirstDayOfWeek());
        monthView.setSelectionColor(getSelectionColor());
        monthView.setDateTextAppearance(adapter.getDateTextAppearance());
        monthView.setWeekDayTextAppearance(adapter.getWeekDayTextAppearance());
        monthView.setShowOtherDates(getShowOtherDates());
        addView(monthView, new LayoutParams(MonthView.DEFAULT_MONTH_TILE_HEIGHT));
    }
}

From source file:com.ruesga.timelinechart.TimelineChartView.java

private void init(Context ctx, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    mUiHandler = new Handler(Looper.getMainLooper(), mMessenger);
    if (!isInEditMode()) {
        mAudioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
    }/*from w  ww. j a v  a2s.  co  m*/

    final Resources res = getResources();
    final Resources.Theme theme = ctx.getTheme();

    mTickFormats = getResources().getStringArray(R.array.tlcDefTickLabelFormats);
    mTickLabels = getResources().getStringArray(R.array.tlcDefTickLabelValues);

    final DisplayMetrics dp = getResources().getDisplayMetrics();
    mSize8 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 8, dp);
    mSize12 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, dp);
    mSize20 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, dp);

    final ViewConfiguration vc = ViewConfiguration.get(ctx);
    mLongPressTimeout = ViewConfiguration.getLongPressTimeout();
    mTouchSlop = vc.getScaledTouchSlop() / 2;
    mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
    mScroller = new OverScroller(ctx);

    int graphBgColor = ContextCompat.getColor(ctx, R.color.tlcDefGraphBackgroundColor);
    int footerBgColor = ContextCompat.getColor(ctx, R.color.tlcDefFooterBackgroundColor);

    mDefFooterBarHeight = mFooterBarHeight = res.getDimension(R.dimen.tlcDefFooterBarHeight);
    mShowFooter = res.getBoolean(R.bool.tlcDefShowFooter);
    mGraphMode = res.getInteger(R.integer.tlcDefGraphMode);
    mPlaySelectionSoundEffect = res.getBoolean(R.bool.tlcDefPlaySelectionSoundEffect);
    mSelectionSoundEffectSource = res.getInteger(R.integer.tlcDefSelectionSoundEffectSource);
    mAnimateCursorTransition = res.getBoolean(R.bool.tlcDefAnimateCursorTransition);
    mFollowCursorPosition = res.getBoolean(R.bool.tlcDefFollowCursorPosition);
    mAlwaysEnsureSelection = res.getBoolean(R.bool.tlcDefAlwaysEnsureSelection);

    mGraphAreaBgPaint = new Paint();
    mGraphAreaBgPaint.setColor(graphBgColor);
    mFooterAreaBgPaint = new Paint();
    mFooterAreaBgPaint.setColor(footerBgColor);
    mTickLabelFgPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
    mTickLabelFgPaint.setFakeBoldText(true);
    mTickLabelFgPaint.setColor(MaterialPaletteHelper.isDarkColor(footerBgColor) ? Color.LTGRAY : Color.DKGRAY);

    mBarItemWidth = res.getDimension(R.dimen.tlcDefBarItemWidth);
    mBarItemSpace = res.getDimension(R.dimen.tlcDefBarItemSpace);

    TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.tlcTimelineChartView, defStyleAttr,
            defStyleRes);
    try {
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            if (attr == R.styleable.tlcTimelineChartView_tlcGraphBackground) {
                graphBgColor = a.getColor(attr, graphBgColor);
                mGraphAreaBgPaint.setColor(graphBgColor);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcShowFooter) {
                mShowFooter = a.getBoolean(attr, mShowFooter);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcFooterBackground) {
                footerBgColor = a.getColor(attr, footerBgColor);
                mFooterAreaBgPaint.setColor(footerBgColor);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcFooterBarHeight) {
                mFooterBarHeight = a.getDimension(attr, mFooterBarHeight);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcGraphMode) {
                mGraphMode = a.getInt(attr, mGraphMode);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcAnimateCursorTransition) {
                mAnimateCursorTransition = a.getBoolean(attr, mAnimateCursorTransition);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcFollowCursorPosition) {
                mFollowCursorPosition = a.getBoolean(attr, mFollowCursorPosition);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcAlwaysEnsureSelection) {
                mAlwaysEnsureSelection = a.getBoolean(attr, mAlwaysEnsureSelection);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcBarItemWidth) {
                mBarItemWidth = a.getDimension(attr, mBarItemWidth);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcBarItemSpace) {
                mBarItemSpace = a.getDimension(attr, mBarItemSpace);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcPlaySelectionSoundEffect) {
                mPlaySelectionSoundEffect = a.getBoolean(attr, mPlaySelectionSoundEffect);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcSelectionSoundEffectSource) {
                mSelectionSoundEffectSource = a.getInt(attr, mSelectionSoundEffectSource);
            }
        }
    } finally {
        a.recycle();
    }

    // SurfaceView requires a background
    if (getBackground() == null) {
        setBackgroundColor(ContextCompat.getColor(ctx, android.R.color.transparent));
    }

    // Minimize the impact of create dynamic layouts by assume that in most case
    // we will have a day formatter
    mTickHasDayFormat = true;

    // Initialize stuff
    setupBackgroundHandler();
    setupTickLabels();
    if (ViewCompat.getOverScrollMode(this) != ViewCompat.OVER_SCROLL_NEVER) {
        setupEdgeEffects();
    }
    setupAnimators();
    setupSoundEffects();

    // Initialize the drawing refs (this will be update when we have
    // the real size of the canvas)
    computeBoundAreas();

    // Create a fake data for the edit mode
    if (isInEditMode()) {
        setupViewInEditMode();
    }
}

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

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

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

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

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

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

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

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

    mMarkerSideLength = mCellSize * MARKER_TRIANGLE_LENGTH_FRACTION;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    mBitmapPaint = new Paint(Paint.FILTER_BITMAP_FLAG);

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

    setFocusableInTouchMode(true);
    setOnKeyListener(this);
}

From source file:org.getlantern.firetweet.util.Utils.java

public static int getActionBarHeight(Context context) {
    final TypedValue tv = new TypedValue();
    final Theme theme = context.getTheme();
    final int attr = context instanceof ActionBarActivity ? R.attr.actionBarSize : android.R.attr.actionBarSize;
    if (theme.resolveAttribute(attr, tv, true)) {
        return TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
    }// w  w  w . j a  va 2 s  .co  m
    return 0;
}

From source file:android.support.v7.widget.AppCompatDrawableManager.java

private Drawable loadDrawableFromDelegates(@NonNull Context context, @DrawableRes int resId) {
    if (mDelegates != null && !mDelegates.isEmpty()) {
        if (mKnownDrawableIdTags != null) {
            final String cachedTagName = mKnownDrawableIdTags.get(resId);
            if (SKIP_DRAWABLE_TAG.equals(cachedTagName)
                    || (cachedTagName != null && mDelegates.get(cachedTagName) == null)) {
                // If we don't have a delegate for the drawable tag, or we've been set to
                // skip it, fail fast and return null
                if (DEBUG) {
                    Log.d(TAG, "[loadDrawableFromDelegates] Skipping drawable: "
                            + context.getResources().getResourceName(resId));
                }//w w  w  .j a  v a2 s .c  om
                return null;
            }
        } else {
            // Create an id cache as we'll need one later
            mKnownDrawableIdTags = new SparseArray<>();
        }

        if (mTypedValue == null) {
            mTypedValue = new TypedValue();
        }
        final TypedValue tv = mTypedValue;
        final Resources res = context.getResources();
        res.getValue(resId, tv, true);

        final long key = createCacheKey(tv);

        Drawable dr = getCachedDrawable(context, key);
        if (dr != null) {
            if (DEBUG) {
                Log.i(TAG, "[loadDrawableFromDelegates] Returning cached drawable: "
                        + context.getResources().getResourceName(resId));
            }
            // We have a cached drawable, return it!
            return dr;
        }

        if (tv.string != null && tv.string.toString().endsWith(".xml")) {
            // If the resource is an XML file, let's try and parse it
            try {
                final XmlPullParser parser = res.getXml(resId);
                final AttributeSet attrs = Xml.asAttributeSet(parser);
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG
                        && type != XmlPullParser.END_DOCUMENT) {
                    // Empty loop
                }
                if (type != XmlPullParser.START_TAG) {
                    throw new XmlPullParserException("No start tag found");
                }

                final String tagName = parser.getName();
                // Add the tag name to the cache
                mKnownDrawableIdTags.append(resId, tagName);

                // Now try and find a delegate for the tag name and inflate if found
                final InflateDelegate delegate = mDelegates.get(tagName);
                if (delegate != null) {
                    dr = delegate.createFromXmlInner(context, parser, attrs, context.getTheme());
                }
                if (dr != null) {
                    // Add it to the drawable cache
                    dr.setChangingConfigurations(tv.changingConfigurations);
                    if (addDrawableToCache(context, key, dr) && DEBUG) {
                        Log.i(TAG, "[loadDrawableFromDelegates] Saved drawable to cache: "
                                + context.getResources().getResourceName(resId));
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "Exception while inflating drawable", e);
            }
        }
        if (dr == null) {
            // If we reach here then the delegate inflation of the resource failed. Mark it as
            // bad so we skip the id next time
            mKnownDrawableIdTags.append(resId, SKIP_DRAWABLE_TAG);
        }
        return dr;
    }

    return null;
}

From source file:org.getlantern.firetweet.util.Utils.java

public static int getActionBarHeight(@Nullable ActionBar actionBar) {
    if (actionBar == null)
        return 0;
    final Context context = actionBar.getThemedContext();
    final TypedValue tv = new TypedValue();
    final int height = actionBar.getHeight();
    if (height > 0)
        return height;
    if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
        return TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
    }//from   w w w  . j  a v a 2  s. c om
    return 0;
}