Java Code Examples for android.content.res.Resources

The following are top voted examples for showing how to use android.content.res.Resources. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: TreebolicLib   File: Utils.java   View source code 7 votes vote down vote up
/**
 * Get drawable
 *
 * @param context context
 * @param resId   drawable id
 * @return drawable
 */
static public Drawable getDrawable(@NonNull final Context context, int resId)
{
	final Resources resources = context.getResources();
	Drawable drawable;
	if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP)
	{
		final Resources.Theme theme = context.getTheme();
		drawable = resources.getDrawable(resId, theme);
	}
	else
	{
		drawable = resources.getDrawable(resId);
	}
	return drawable;
}
 
Example 2
Project: GitHub   File: MDRootLayout.java   View source code 6 votes vote down vote up
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
    Resources r = context.getResources();

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MDRootLayout, defStyleAttr, 0);
    reducePaddingNoTitleNoButtons = a.getBoolean(R.styleable.MDRootLayout_md_reduce_padding_no_title_no_buttons, true);
    a.recycle();

    noTitlePaddingFull = r.getDimensionPixelSize(R.dimen.md_notitle_vertical_padding);
    buttonPaddingFull = r.getDimensionPixelSize(R.dimen.md_button_frame_vertical_padding);

    buttonHorizontalEdgeMargin = r.getDimensionPixelSize(R.dimen.md_button_padding_frame_side);
    buttonBarHeight = r.getDimensionPixelSize(R.dimen.md_button_height);

    dividerPaint = new Paint();
    dividerWidth = r.getDimensionPixelSize(R.dimen.md_divider_height);
    dividerPaint.setColor(DialogUtils.resolveColor(context, R.attr.md_divider_color));
    setWillNotDraw(false);
}
 
Example 3
Project: FastTextView   File: FastTextView.java   View source code 6 votes vote down vote up
private void init(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int
    defStyleRes) {
  mAttrsHelper.init(context, attrs, defStyleAttr, defStyleRes);
  setText(mAttrsHelper.mText);
  TextPaint textPaint = getTextPaint();
  textPaint.setColor(mAttrsHelper.mTextColor);
  textPaint.setTextSize(mAttrsHelper.mTextSize);
  final Resources.Theme theme = context.getTheme();
  TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.FastTextView, defStyleAttr,
      defStyleRes);
  mEnableLayoutCache = a.getBoolean(R.styleable.FastTextView_enableLayoutCache, false);
  a.recycle();
}
 
Example 4
Project: sflauncher   File: App.java   View source code 6 votes vote down vote up
private static Shortcut from(Card.Apps c, String ident){
    String[] parts = ident.split("\\|");
    Context ctx = c.getWrapper().getContext();
    if(parts[0].equals("shortcut4") && parts.length >= 5){
        try {
            Resources res = ctx.getPackageManager().getResourcesForApplication(parts[1]);
            int drawableIdent = res.getIdentifier(parts[4], "drawable", parts[1]);
            Drawable icon = res.getDrawable(drawableIdent);
            String uri = decodeText(parts[2]);
            Intent intent = Intent.parseUri(uri, Intent.URI_INTENT_SCHEME);
            return new Shortcut(parts[3], icon, parts[1], intent, drawableIdent);
        } catch (PackageManager.NameNotFoundException | URISyntaxException |
                    Resources.NotFoundException ignored) {
        }
    }
    return null;
}
 
Example 5
Project: GitHub   File: SystemBarTintManager.java   View source code 6 votes vote down vote up
@TargetApi(14)
private int getNavigationBarHeight(Context context) {
    Resources res = context.getResources();
    int result = 0;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        if (hasNavBar(context)) {
            String key;
            if (mInPortrait) {
                key = NAV_BAR_HEIGHT_RES_NAME;
            } else {
                key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME;
            }
            return getInternalDimensionSize(res, key);
        }
    }
    return result;
}
 
Example 6
Project: AliZhiBoHao   File: MenuDialog.java   View source code 6 votes vote down vote up
private void init(Context context) {
    setOrientation(VERTICAL);

    Resources r = context.getResources();
    int pxPadding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, r.getDisplayMetrics());

    setPadding(pxPadding, pxPadding, pxPadding, pxPadding);

    LayoutInflater layoutInflater = LayoutInflater.from(context);
    View view = layoutInflater.inflate(R.layout.menu_dialog, this);
    mStreamEditText = (EditText) view.findViewById(R.id.stream_url);
    mResolutionGroup = (RadioGroup)view.findViewById(R.id.resolution);
    mResolutionGroup.check(R.id.resolution_hight);

    mOrientationGroup = (RadioGroup)view.findViewById(R.id.orientation);
    mOrientationGroup.check(R.id.orientation_landscape);
}
 
Example 7
Project: Hands-On-Android-UI-Development   File: ItemPresenter.java   View source code 6 votes vote down vote up
public Drawable getCategoryIcon(final Category category) {
    final Resources resources = context.getResources();

    switch (category) {
        case ACCOMMODATION:
            return resources.getDrawable(R.drawable.ic_hotel_black);
        case FOOD:
            return resources.getDrawable(R.drawable.ic_food_black);
        case TRANSPORT:
            return resources.getDrawable(R.drawable.ic_transport_black);
        case ENTERTAINMENT:
            return
                    resources.getDrawable(R.drawable.ic_entertainment_black);
        case BUSINESS:
            return resources.getDrawable(R.drawable.ic_business_black);
        case OTHER:
        default:
            return resources.getDrawable(R.drawable.ic_other_black);
    }
}
 
Example 8
Project: RLibrary   File: BitmapUtil.java   View source code 6 votes vote down vote up
/**
 * 获取压缩后的图片
 *
 * @param res
 * @param resId
 * @param reqWidth  所需图片压缩尺寸最小宽度
 * @param reqHeight 所需图片压缩尺寸最小高度
 * @return
 */
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
    /**
     * 1.获取图片的像素宽高(不加载图片至内存中,所以不会占用资源)
     * 2.计算需要压缩的比例
     * 3.按将图片用计算出的比例压缩,并加载至内存中使用
     */
    // 首先不加载图片,仅获取图片尺寸
    final BitmapFactory.Options options = new BitmapFactory.Options();
    // 当inJustDecodeBounds设为true时,不会加载图片仅获取图片尺寸信息
    options.inJustDecodeBounds = true;
    // 此时仅会将图片信息会保存至options对象内,decode方法不会返回bitmap对象
    BitmapFactory.decodeResource(res, resId, options);

    // 计算压缩比例,如inSampleSize=4时,图片会压缩成原图的1/4
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // 当inJustDecodeBounds设为false时,BitmapFactory.decode...就会返回图片对象了
    options.inJustDecodeBounds = false;
    options.inScaled = false;
    // 利用计算的比例值获取压缩后的图片对象
    return BitmapFactory.decodeResource(res, resId, options);
}
 
Example 9
Project: cwac-crossport   File: FloatingActionButton.java   View source code 6 votes vote down vote up
private int getSizeDimension(@Size final int size) {
  final Resources res = getResources();
  switch (size) {
    case SIZE_AUTO:
      // If we're set to auto, grab the size from resources and refresh
              final int width = res.getConfiguration().screenWidthDp;
              final int height = res.getConfiguration().screenHeightDp;
      return Math.max(width, height) < AUTO_MINI_LARGEST_SCREEN_WIDTH
          ? getSizeDimension(SIZE_MINI)
          : getSizeDimension(SIZE_NORMAL);
    case SIZE_MINI:
      return res.getDimensionPixelSize(R.dimen.design_fab_size_mini);
    case SIZE_NORMAL:
    default:
      return res.getDimensionPixelSize(R.dimen.design_fab_size_normal);
  }
}
 
Example 10
Project: meat-grinder   File: ResultItemHolder.java   View source code 6 votes vote down vote up
public void onBind(@NonNull CheckInfo checkInfo, int position) {
    if (mCheckInfo != null && mCheckInfo.equals(checkInfo)) {
        return;
    }
    mCheckInfo = checkInfo;
    Resources res = itemView.getResources();
    String desc = res.getString(ChecksHelper.getCheckStringId(mCheckInfo.getTypeCheck()));
    title.setText(desc);
    if (mCheckInfo.getState() == null) {
        icon.setImageBitmap(getNonCheck(itemView.getContext()));
    } else if (mCheckInfo.getState() == Boolean.TRUE) {
        icon.setImageBitmap(getFound(itemView.getContext()));
    } else {
        icon.setImageBitmap(getOk(itemView.getContext()));
    }

}
 
Example 11
Project: ImmerseMode   File: ActivityConfig.java   View source code 6 votes vote down vote up
private int getNavigationBarHeight(Context context) {
    Resources res = context.getResources();
    int result = 0;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        if (hasNavBar(context)) {
            String key;
            if (mInPortrait) {
                key = NAV_BAR_HEIGHT_RES_NAME;
            } else {
                key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME;
            }
            return ResourcesUtils.getDimensionSize(res, key, "android");
        }
    }
    return result;
}
 
Example 12
Project: aarLibrary   File: XRefreshViewHeader.java   View source code 6 votes vote down vote up
public void setRefreshTime(long lastRefreshTime) {
    // 获取当前时间
    Calendar mCalendar = Calendar.getInstance();
    long refreshTime = mCalendar.getTimeInMillis();
    long howLong = refreshTime - lastRefreshTime;
    int minutes = (int) (howLong / 1000 / 60);
    String refreshTimeText = null;
    Resources resources = getContext().getResources();
    if (minutes < 1) {
        refreshTimeText = resources
                .getString(R.string.xrefreshview_refresh_justnow);
    } else if (minutes < 60) {
        refreshTimeText = resources
                .getString(R.string.xrefreshview_refresh_minutes_ago);
        refreshTimeText = Utils.format(refreshTimeText, minutes);
    } else if (minutes < 60 * 24) {
        refreshTimeText = resources
                .getString(R.string.xrefreshview_refresh_hours_ago);
        refreshTimeText = Utils.format(refreshTimeText, minutes / 60);
    } else {
        refreshTimeText = resources
                .getString(R.string.xrefreshview_refresh_days_ago);
        refreshTimeText = Utils.format(refreshTimeText, minutes / 60 / 24);
    }
    mHeaderTimeTextView.setText(refreshTimeText);
}
 
Example 13
Project: LaunchEnr   File: AutoInstallsLayout.java   View source code 6 votes vote down vote up
AutoInstallsLayout(Context context, AppWidgetHost appWidgetHost,
        LayoutParserCallback callback, Resources res,
        int layoutId, String rootTag) {
    mContext = context;
    mAppWidgetHost = appWidgetHost;
    mCallback = callback;

    mPackageManager = context.getPackageManager();
    mValues = new ContentValues();
    mRootTag = rootTag;

    mSourceRes = res;
    mLayoutId = layoutId;

    mIdp = LauncherAppState.getIDP(context);
    mRowCount = mIdp.numRows;
    mColumnCount = mIdp.numColumns;
}
 
Example 14
Project: SimpleUILauncher   File: Workspace.java   View source code 6 votes vote down vote up
/**
 * Used to inflate the Workspace from XML.
 *
 * @param context The application's context.
 * @param attrs The attributes set containing the Workspace's customization values.
 * @param defStyle Unused.
 */
public Workspace(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    mLauncher = Launcher.getLauncher(context);
    mStateTransitionAnimation = new WorkspaceStateTransitionAnimation(mLauncher, this);
    final Resources res = getResources();
    DeviceProfile grid = mLauncher.getDeviceProfile();
    mWorkspaceFadeInAdjacentScreens = grid.shouldFadeAdjacentWorkspaceScreens();
    mWallpaperManager = WallpaperManager.getInstance(context);

    mWallpaperOffset = new WallpaperOffsetInterpolator(this);
    mOverviewModeShrinkFactor =
            res.getInteger(R.integer.config_workspaceOverviewShrinkPercentage) / 100f;

    setOnHierarchyChangeListener(this);
    setHapticFeedbackEnabled(false);

    initWorkspace();

    // Disable multitouch across the workspace/all apps/customize tray
    setMotionEventSplittingEnabled(true);
}
 
Example 15
Project: SimpleUILauncher   File: DragLayer.java   View source code 6 votes vote down vote up
/**
 * Used to create a new DragLayer from XML.
 *
 * @param context The application's context.
 * @param attrs The attributes set containing the Workspace's customization values.
 */
public DragLayer(Context context, AttributeSet attrs) {
    super(context, attrs);

    // Disable multitouch across the workspace/all apps/customize tray
    setMotionEventSplittingEnabled(false);
    setChildrenDrawingOrderEnabled(true);

    final Resources res = getResources();
    mLeftHoverDrawable = res.getDrawable(R.drawable.page_hover_left);
    mRightHoverDrawable = res.getDrawable(R.drawable.page_hover_right);
    mLeftHoverDrawableActive = res.getDrawable(R.drawable.page_hover_left_active);
    mRightHoverDrawableActive = res.getDrawable(R.drawable.page_hover_right_active);
    mIsRtl = Utilities.isRtl(res);
    mFocusIndicatorHelper = new ViewGroupFocusHelper(this);
}
 
Example 16
Project: SuperSelector   File: ImageResizer.java   View source code 6 votes vote down vote up
/**
 * Decode and sample down a bitmap from resources to the requested width and
 * height.
 * 
 * @param res
 *            The resources object containing the image data
 * @param resId
 *            The resource id of the image data
 * @param reqWidth
 *            The requested width of the resulting bitmap
 * @param reqHeight
 *            The requested height of the resulting bitmap
 * @param cache
 *            The ImageCache used to find candidate bitmaps for use with
 *            inBitmap
 * @return A bitmap sampled down from the original with the same aspect
 *         ratio and dimensions that are equal to or greater than the
 *         requested width and height
 */
public static Bitmap decodeSampledBitmapFromResource(Resources res,
                                                        int resId, int reqWidth, int reqHeight, ImageCache cache) {

	// BEGIN_INCLUDE (read_bitmap_dimensions)
	// First decode with inJustDecodeBounds=true to check dimensions
	final BitmapFactory.Options options = new BitmapFactory.Options();
	options.inJustDecodeBounds = true;
	BitmapFactory.decodeResource(res, resId, options);

	// Calculate inSampleSize
	options.inSampleSize = calculateInSampleSize(options, reqWidth,
			reqHeight);
	// END_INCLUDE (read_bitmap_dimensions)

	// If we're running on Honeycomb or newer, try to use inBitmap
	if (Utils.hasHoneycomb()) {
		addInBitmapOptions(options, cache);
	}

	// Decode bitmap with inSampleSize set
	options.inJustDecodeBounds = false;
	return BitmapFactory.decodeResource(res, resId, options);
}
 
Example 17
Project: microMathematics   File: AppLocale.java   View source code 6 votes vote down vote up
@SuppressWarnings("deprecation")
public static ContextWrapper wrap(Context context, Locale newLocale)
{
    final Resources res = context.getResources();
    final Configuration configuration = res.getConfiguration();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
    {
        configuration.setLocale(newLocale);
        LocaleList localeList = new LocaleList(newLocale);
        LocaleList.setDefault(localeList);
        configuration.setLocales(localeList);
        context = context.createConfigurationContext(configuration);
    }
    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
    {
        configuration.setLocale(newLocale);
        context = context.createConfigurationContext(configuration);
    }
    else
    {
        configuration.locale = newLocale;
        res.updateConfiguration(configuration, res.getDisplayMetrics());
    }
    return new ContextWrapper(context);
}
 
Example 18
Project: FlickLauncher   File: AllAppsContainerView.java   View source code 6 votes vote down vote up
public AllAppsContainerView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    Resources res = context.getResources();

    mLauncher = Launcher.getLauncher(context);
    mSectionNamesMargin = res.getDimensionPixelSize(R.dimen.all_apps_grid_view_start_margin);
    mApps = new AlphabeticalAppsList(context);
    mAdapter = new AllAppsGridAdapter(mLauncher, mApps, mLauncher, this);
    mApps.setAdapter(mAdapter);
    mLayoutManager = mAdapter.getLayoutManager();
    mItemDecoration = mAdapter.getItemDecoration();
    DeviceProfile grid = mLauncher.getDeviceProfile();
    if (FeatureFlags.LAUNCHER3_ALL_APPS_PULL_UP && !grid.isVerticalBarLayout()) {
        mRecyclerViewBottomPadding = 0;
        setPadding(0, 0, 0, 0);
    } else {
        mRecyclerViewBottomPadding =
                res.getDimensionPixelSize(R.dimen.all_apps_list_bottom_padding);
    }
    mSearchQueryBuilder = new SpannableStringBuilder();
    Selection.setSelection(mSearchQueryBuilder, 0);

}
 
Example 19
Project: HeroVideo-master   File: MediaPlayer.java   View source code 5 votes vote down vote up
public float pixel2dip(Context context, float n){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = n / (metrics.densityDpi / 160f);
    return dp;

}
 
Example 20
Project: ClouldReader   File: CloudReaderApplication.java   View source code 5 votes vote down vote up
/**
 * 使其系统更改字体大小无效
 */
private void initTextSize() {
    Resources res = getResources();
    Configuration config = new Configuration();
    config.setToDefaults();
    res.updateConfiguration(config, res.getDisplayMetrics());
}
 
Example 21
Project: phonk   File: PUtil.java   View source code 5 votes vote down vote up
@ProtoMethod(description = "Convert given dp to pixels", example = "")
@ProtoMethodParam(params = {""})
public float dpToPixels(float dp) {
    Resources resources = getContext().getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return px;
}
 
Example 22
Project: firefox-tv   File: ErrorPage.java   View source code 5 votes vote down vote up
public static void loadErrorPage(final AmazonWebView webView, final String desiredURL, final int errorCode) {
    final Pair<Integer, Integer> errorResourceIDs = errorDescriptionMap.get(errorCode);

    if (errorResourceIDs == null) {
        throw new IllegalArgumentException("Cannot load error description for unsupported errorcode=" + errorCode);
    }

    // This is quite hacky: ideally we'd just load the css file directly using a '<link rel="stylesheet"'.
    // However WebView thinks it's still loading the original page, which can be an https:// page.
    // If mixed content blocking is enabled (which is probably what we want in Focus), then webkit
    // will block file:///android_res/ links from being loaded - which blocks our css from being loaded.
    // We could hack around that by enabling mixed content when loading an error page (and reenabling it
    // once that's loaded), but doing that correctly and reliably isn't particularly simple. Loading
    // the css data and stuffing it into our html is much simpler, especially since we're already doing
    // string substitutions.
    // As an added bonus: file:/// URIs are broken if the app-ID != app package, see:
    // https://code.google.com/p/android/issues/detail?id=211768 (this breaks loading css via file:///
    // references when running debug builds, and probably klar too) - which means this wouldn't
    // be possible even if we hacked around the mixed content issues.
    final String cssString = HtmlLoader.loadResourceFile(webView.getContext(), R.raw.errorpage_style, null);

    final Map<String, String> substitutionMap = new ArrayMap<>();

    final Resources resources = webView.getContext().getResources();

    substitutionMap.put("%page-title%", resources.getString(R.string.errorpage_title));
    substitutionMap.put("%button%", resources.getString(R.string.errorpage_refresh));

    substitutionMap.put("%messageShort%", resources.getString(errorResourceIDs.first));
    substitutionMap.put("%messageLong%", resources.getString(errorResourceIDs.second, desiredURL));

    substitutionMap.put("%css%", cssString);

    final String errorPage = HtmlLoader.loadResourceFile(webView.getContext(), R.raw.errorpage, substitutionMap);

    // We could load the raw html file directly into the webview using a file:///android_res/
    // URI - however we'd then need to do some JS hacking to do our String substitutions. Moreover
    // we'd have to deal with the mixed-content issues detailed above in that case.
    webView.loadDataWithBaseURL(desiredURL, errorPage, "text/html", "UTF8", desiredURL);
}
 
Example 23
Project: Android-2017   File: MainActivity.java   View source code 5 votes vote down vote up
@Override
public void onClick (View view) {
    String strNumeroGatitos;
    int intNumeroGatitos = -1;
    // objeto recursos para el acceso a los mismos
    Resources res = this.getResources();

    // recuperar la vista con la respuesta a la pregunta
    EditText txtGatitos  = (EditText) findViewById(R.id.preguntaGatitos);
    // recuperar la respuesta a la pregunta (como texto)
    strNumeroGatitos = txtGatitos.getText().toString();

    try {
        // convertir el valor introducido en el Edit Text a numerico
        intNumeroGatitos = Integer.parseInt(strNumeroGatitos);
    }
    catch (NumberFormatException ex) {
        // controlamos el error en caso que no se haya introducido un numero
        Toast.makeText(this, R.string.error_numerico, Toast.LENGTH_LONG).show();
        intNumeroGatitos = -1;
    }

    // mostrar un mensaje en función del número de gatitos
    if (intNumeroGatitos != -1) {
        // recuepramos la vista respuesta
        TextView txtRespuesta = (TextView) findViewById(R.id.respuestaGatitos);
        // el segundo parámetro sirve para seleccional que forma se ha de usar.
        // el tercer parámetro es opcional. Si se ha indicado formato en la cadena un formato debemos indicar aquí
        // los parámetros requeridos.
        txtRespuesta.setText(res.getQuantityString(R.plurals.gatitos, intNumeroGatitos, intNumeroGatitos));

    }
}
 
Example 24
Project: simple-stack   File: TasksPresenter.java   View source code 5 votes vote down vote up
@Inject
public TasksPresenter(Backstack backstack, TaskRepository taskRepository, MessageQueue messageQueue, Resources resources) {
    this.backstack = backstack;
    this.taskRepository = taskRepository;
    this.messageQueue = messageQueue;
    this.resources = resources;
}
 
Example 25
Project: easyfilemanager   File: MaterialProgressDialog.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Resources res = getContext().getResources();
    mDefaultColor = res.getColor(R.color.accentColor);

    indeterminateDrawable = new MaterialProgressDrawable(getContext(), findViewById(android.R.id.progress));
    indeterminateDrawable.setBackgroundColor(CIRCLE_BG_LIGHT);
    indeterminateDrawable.setAlpha(255);
    indeterminateDrawable.updateSizes(MaterialProgressDrawable.XLARGE);
    indeterminateDrawable.setColorSchemeColors(getColor());
    indeterminateDrawable.start();
    setIndeterminateDrawable(indeterminateDrawable);
}
 
Example 26
Project: igrow-android   File: EnvironmentalSensorsViewModelTest.java   View source code 5 votes vote down vote up
private void setupContext() {
    when(mContext.getApplicationContext()).thenReturn(mContext);
    when(mContext.getString(R.string.successfully_saved_sensor_message))
            .thenReturn("EDIT_RESULT_OK");
    when(mContext.getString(R.string.successfully_added_sensor_message))
            .thenReturn("ADD_EDIT_RESULT_OK");
    when(mContext.getString(R.string.successfully_deleted_sensor_message))
            .thenReturn("DELETE_RESULT_OK");

    when(mContext.getResources()).thenReturn(mock(Resources.class));
}
 
Example 27
Project: chromium-for-android-56-debug-video   File: MostVisitedLayout.java   View source code 5 votes vote down vote up
/**
 * @param context The view context in which this item will be shown.
 * @param attrs The attributes of the XML tag that is inflating the view.
 */
public MostVisitedLayout(Context context, AttributeSet attrs) {
    super(context, attrs);

    Resources res = getResources();
    mVerticalSpacing = res.getDimensionPixelOffset(R.dimen.most_visited_vertical_spacing);
    mMinHorizontalSpacing = res.getDimensionPixelOffset(
            R.dimen.most_visited_min_horizontal_spacing);
    mMaxHorizontalSpacing = res.getDimensionPixelOffset(
            R.dimen.most_visited_max_horizontal_spacing);
    mMaxWidth = res.getDimensionPixelOffset(R.dimen.most_visited_layout_max_width);
}
 
Example 28
Project: KUtils   File: SystemBarTintManager.java   View source code 5 votes vote down vote up
private int getInternalDimensionSize(Resources res, String key) {
    int result = 0;
    int resourceId = res.getIdentifier(key, "dimen", "android");
    if (resourceId > 0) {
        result = res.getDimensionPixelSize(resourceId);
    }
    return result;
}
 
Example 29
Project: JPSpringMenu   File: SpringMenu.java   View source code 5 votes vote down vote up
private int getStatusBarHeight() {
    Resources resources = getResources();
    int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        return resources.getDimensionPixelSize(resourceId);
    }
    return 0;
}
 
Example 30
Project: LucaHome-MediaServer   File: SnakeView.java   View source code 5 votes vote down vote up
@SuppressWarnings("deprecation")
private void initSnakeView() {
    _logger = new SmartMirrorLogger(TAG);
    _logger.Debug("SnakeView created...");

    setFocusable(true);

    Resources resources = this.getContext().getResources();

    ResetTiles(4);

    LoadTile(RED_STAR, resources.getDrawable(R.drawable.redstar));
    LoadTile(YELLOW_STAR, resources.getDrawable(R.drawable.yellowstar));
    LoadTile(GREEN_STAR, resources.getDrawable(R.drawable.greenstar));
}
 
Example 31
Project: chromium-for-android-56-debug-video   File: NotificationBuilderBase.java   View source code 5 votes vote down vote up
public NotificationBuilderBase(Resources resources) {
    mLargeIconWidthPx =
            resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
    mLargeIconHeightPx =
            resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
    mIconGenerator = createIconGenerator(resources);
}
 
Example 32
Project: android_ui   File: LinearProgressDrawable.java   View source code 5 votes vote down vote up
/**
 * Creates a new instance of LinearProgressDrawable from the specified <var>state</var>.
 *
 * @param state The state from which to create the new progress drawable instance.
 * @param res   An application resources.
 * @param theme A theme to be applied to the new progress drawable instance.
 */
private LinearProgressDrawable(LinearState state, Resources res, Resources.Theme theme) {
	if (theme != null && state.canApplyTheme()) {
		changeConstantState(mProgressState = new LinearState(state));
		applyTheme(theme);
	} else {
		changeConstantState(mProgressState = state);
	}
	this.mBackgroundTintFilter = TintDrawable.createTintFilter(this, state.backgroundTint, state.backgroundTintMode);
	this.mProgressTintFilter = TintDrawable.createTintFilter(this, state.progressTint, state.progressTintMode);
	this.mSecondaryProgressTintFilter = TintDrawable.createTintFilter(this, state.secondaryProgressTint, state.secondaryProgressTintMode);
	this.mIndeterminateTintFilter = TintDrawable.createTintFilter(this, state.indeterminateTint, state.indeterminateTintMode);
}
 
Example 33
Project: brickkit-android   File: BrickSizeTest.java   View source code 5 votes vote down vote up
@Before
public void setup() {
    configuration = new Configuration();

    resources = mock(Resources.class);
    when(resources.getConfiguration()).thenReturn(configuration);

    context = mock(Context.class);
    when(context.getResources()).thenReturn(resources);

    brick = mock(BaseBrick.class);

    brickSize = new TestBrickSize();
    brickSize.setBaseBrick(brick);
}
 
Example 34
Project: mvvm-template   File: DynamicRecyclerView.java   View source code 5 votes vote down vote up
public void addKeyLineDivider() {
    if (canAddDivider()) {
        Resources resources = getResources();
        addItemDecoration(new InsetDividerDecoration(resources.getDimensionPixelSize(R.dimen.divider_height),
                resources.getDimensionPixelSize(R.dimen.keyline_2), ViewHelper.getListDivider(getContext())));
    }
}
 
Example 35
Project: GitHub   File: DeviceInfoTests.java   View source code 5 votes vote down vote up
private Context mockContextForTestingDensity(final int density) {
    final DisplayMetrics metrics = new DisplayMetrics();
    metrics.densityDpi = density;
    final Resources mockResources = mock(Resources.class);
    when(mockResources.getDisplayMetrics()).thenReturn(metrics);
    final Context mockContext = mock(Context.class);
    when(mockContext.getResources()).thenReturn(mockResources);
    return mockContext;
}
 
Example 36
Project: KUtils-master   File: SystemBarTintManager.java   View source code 5 votes vote down vote up
private int getInternalDimensionSize(Resources res, String key) {
    int result = 0;
    int resourceId = res.getIdentifier(key, "dimen", "android");
    if (resourceId > 0) {
        result = res.getDimensionPixelSize(resourceId);
    }
    return result;
}
 
Example 37
Project: AssistantBySDK   File: LingjuSwipeRefreshLayout.java   View source code 5 votes vote down vote up
/**
 * Set the color resources used in the progress animation from color resources.
 * The first color will also be the color of the bar that grows in response
 * to a user swipe gesture.
 *
 * @param colorResIds
 */
public void setColorSchemeResources(int... colorResIds) {
    final Resources res = getResources();
    int[] colorRes = new int[colorResIds.length];
    for (int i = 0; i < colorResIds.length; i++) {
        colorRes[i] = res.getColor(colorResIds[i]);
    }
    setColorSchemeColors(colorRes);
}
 
Example 38
Project: FireFiles   File: ConnectionsFragment.java   View source code 5 votes vote down vote up
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    final Resources res = getActivity().getResources();

    fab = (FloatingActionButton)view.findViewById(R.id.fab);
    fab.setOnClickListener(this);
    if(isTelevision()){
        fab.setVisibility(View.GONE);
    }

    mProgressBar = (MaterialProgressBar) view.findViewById(R.id.progressBar);
    mEmptyView = (CompatTextView)view.findViewById(android.R.id.empty);
    mListView = (ListView) view.findViewById(R.id.list);
    mListView.setOnItemClickListener(mItemListener);
    if(isTelevision()) {
        mListView.setOnItemLongClickListener(mItemLongClickListener);
    }
    fab.attachToListView(mListView);

    // Indent our list divider to align with text
    final Drawable divider = mListView.getDivider();
    final boolean insetLeft = res.getBoolean(R.bool.list_divider_inset_left);
    final int insetSize = res.getDimensionPixelSize(R.dimen.list_divider_inset);
    if (insetLeft) {
        mListView.setDivider(new InsetDrawable(divider, insetSize, 0, 0, 0));
    } else {
        mListView.setDivider(new InsetDrawable(divider, 0, 0, insetSize, 0));
    }
}
 
Example 39
Project: grafika   File: ReadPixelsActivity.java   View source code 5 votes vote down vote up
@Override
protected void onPostExecute(Long result) {
    Log.d(TAG, "onPostExecute result=" + result);
    mDialog.dismiss();
    mDialog = null;

    Resources res = getResources();
    if (result < 0) {
        setMessage(mResultTextId, res.getString(R.string.did_not_complete));
    } else {
        setMessage(mResultTextId, (result / 1000) +
                res.getString(R.string.usec_per_iteration));
    }
}
 
Example 40
Project: GitHub   File: GlideRequest.java   View source code 5 votes vote down vote up
/**
 * @see GlideOptions#theme(Resources.Theme)
 */
@CheckResult
public GlideRequest<TranscodeType> theme(@Nullable Resources.Theme arg0) {
  if (getMutableOptions() instanceof GlideOptions) {
    this.requestOptions = ((GlideOptions) getMutableOptions()).theme(arg0);
  } else {
    this.requestOptions = new GlideOptions().apply(this.requestOptions).theme(arg0);
  }
  return this;
}