Example usage for android.content.res Resources getIdentifier

List of usage examples for android.content.res Resources getIdentifier

Introduction

In this page you can find the example usage for android.content.res Resources getIdentifier.

Prototype

public int getIdentifier(String name, String defType, String defPackage) 

Source Link

Document

Return a resource identifier for the given resource name.

Usage

From source file:fr.tvbarthel.apps.simpleweatherforcast.MainActivity.java

private void initRootPadding() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        final Resources resources = getResources();
        final boolean isPortrait = resources.getBoolean(R.bool.is_portrait);
        final ActionBar actionBar = getSupportActionBar();

        final ViewTreeObserver vto = mRootView.getViewTreeObserver();
        if (vto.isAlive()) {
            vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override// w  w w  . j a va  2  s  .  com
                public boolean onPreDraw() {
                    mRootView.getViewTreeObserver().removeOnPreDrawListener(this);

                    int paddingBottom = mRootView.getPaddingBottom();
                    int paddingTop = mRootView.getPaddingTop();
                    int paddingRight = mRootView.getPaddingRight();
                    int paddingLeft = mRootView.getPaddingLeft();

                    // Add the status bar height to the top padding.
                    int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
                    if (resourceId > 0) {
                        paddingTop += resources.getDimensionPixelSize(resourceId);
                    }

                    if (isPortrait) {
                        // Add the navigation bar height to the bottom padding.
                        resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
                        if (resourceId > 0) {
                            paddingBottom += resources.getDimensionPixelSize(resourceId);
                        }
                    } else {
                        // Add the navigation bar width to the right padding.
                        resourceId = resources.getIdentifier("navigation_bar_width", "dimen", "android");
                        if (resourceId > 0) {
                            paddingRight += resources.getDimensionPixelSize(resourceId);
                        }
                    }

                    mRootView.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
                    return true;
                }
            });
        }
    }
}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowser.java

/**
* This is a rather unintuitive helper method to load images. The reason why this method exists
* is because due to some service limitations, one may not be able to add images to native
* resource bundle. So this method offers a way to load image from www contents instead.
* However loading from native resource bundle is already preferred over loading from www. So
* if name is given, then it simply loads from resource bundle and the other two parameters are
* ignored. If name is not given, then altPath is assumed to be a file path _under_ www and
* altDensity is the desired density of the given image file, because without native resource
* bundle, we can't tell what density the image is supposed to be so it needs to be given
* explicitly.//w w w .j  a  v  a2s  . co  m
*/
private Drawable getImage(String name, String altPath, double altDensity) throws IOException {
    Drawable result = null;
    Resources activityRes = cordova.getActivity().getResources();

    if (name != null) {
        int id = activityRes.getIdentifier(name, "drawable", cordova.getActivity().getPackageName());
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            result = activityRes.getDrawable(id);
        } else {
            result = activityRes.getDrawable(id, cordova.getActivity().getTheme());
        }
    } else if (altPath != null) {
        File file = new File("www", altPath);
        InputStream is = null;
        try {
            is = cordova.getActivity().getAssets().open(file.getPath());
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            bitmap.setDensity((int) (DisplayMetrics.DENSITY_MEDIUM * altDensity));
            result = new BitmapDrawable(activityRes, bitmap);
        } finally {
            // Make sure we close this input stream to prevent resource leak.
            try {
                is.close();
            } catch (Exception e) {
            }
        }
    }
    return result;
}

From source file:com.androidclub.source.XmlDocumentProvider.java

/**
 * Creates an XmlPullParser for the provided local resource. Can be overloaded to provide your
 * own parser.//from   ww  w. j av  a 2  s.  c  om
 * @param resourceUri A fully qualified resource name referencing a local XML resource.
 * @return An XmlPullParser on this resource.
 */
protected XmlPullParser getResourceXmlPullParser(Uri resourceUri) {
    //OpenResourceIdResult resourceId;
    try {
        String authority = resourceUri.getAuthority();
        Resources r;
        if (TextUtils.isEmpty(authority)) {
            throw new FileNotFoundException("No authority: " + resourceUri);
        } else {
            try {
                r = getContext().getPackageManager().getResourcesForApplication(authority);
            } catch (NameNotFoundException ex) {
                throw new FileNotFoundException("No package found for authority: " + resourceUri);
            }
        }
        List<String> path = resourceUri.getPathSegments();
        if (path == null) {
            throw new FileNotFoundException("No path: " + resourceUri);
        }
        int len = path.size();
        int id;
        if (len == 1) {
            try {
                id = Integer.parseInt(path.get(0));
            } catch (NumberFormatException e) {
                throw new FileNotFoundException("Single path segment is not a resource ID: " + resourceUri);
            }
        } else if (len == 2) {
            id = r.getIdentifier(path.get(1), path.get(0), authority);
        } else {
            throw new FileNotFoundException("More than two path segments: " + resourceUri);
        }
        if (id == 0) {
            throw new FileNotFoundException("No resource found for: " + resourceUri);
        }

        return r.getXml(id);
    } catch (FileNotFoundException e) {
        Log.w(LOG_TAG, "XML resource not found: " + resourceUri.toString(), e);
        return null;
    }
}

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

/**
 * Applies a style to the map overlays associated with a given location provider.
 * //ww  w .  ja v  a 2s  . co m
 * This method changes the style (effectively, the color) of the circle and
 * marker overlays. Its main purpose is to switch the color of the overlays
 * between gray and the provider color.
 * 
 * @param context The context of the caller
 * @param provider The name of the location provider, as returned by
 * {@link LocationProvider.getName()}.
 * @param styleName The name of the style to apply. If it is null, the
 * default style for the provider as returned by 
 * assignLocationProviderStyle() is applied. 
 */
protected static void applyLocationProviderStyle(Context context, String provider, String styleName) {
    String sn = (styleName != null) ? styleName : assignLocationProviderStyle(provider);

    Boolean isStyleChanged = !sn.equals(providerAppliedStyles.get(provider));
    Boolean needsRedraw = false;

    Resources res = context.getResources();
    TypedArray style = res.obtainTypedArray(res.getIdentifier(sn, "array", context.getPackageName()));

    // Circle layer
    Circle circle = mapCircles.get(provider);
    if (circle != null) {
        circle.getPaintFill().setColor(style.getColor(STYLE_FILL, R.color.circle_gray_fill));
        circle.getPaintStroke().setColor(style.getColor(STYLE_STROKE, R.color.circle_gray_stroke));
        needsRedraw = isStyleChanged && circle.isVisible();
    }

    //Marker layer
    Marker marker = mapMarkers.get(provider);
    if (marker != null) {
        Drawable drawable = style.getDrawable(STYLE_MARKER);
        Bitmap bitmap = AndroidGraphicFactory.convertToBitmap(drawable);
        marker.setBitmap(bitmap);
        needsRedraw = needsRedraw || (isStyleChanged && marker.isVisible());
    }

    if (needsRedraw)
        mapMap.getLayerManager().redrawLayers();
    providerAppliedStyles.put(provider, sn);
    style.recycle();
}

From source file:cm.aptoide.com.actionbarsherlock.widget.SuggestionsAdapter.java

public Drawable getTheDrawable(Uri uri) throws FileNotFoundException {
    String authority = uri.getAuthority();
    Resources r;
    if (TextUtils.isEmpty(authority)) {
        throw new FileNotFoundException("No authority: " + uri);
    } else {//from w ww  .java 2 s  .co m
        try {
            r = mContext.getPackageManager().getResourcesForApplication(authority);
        } catch (NameNotFoundException ex) {
            throw new FileNotFoundException("No package found for authority: " + uri);
        }
    }
    List<String> path = uri.getPathSegments();
    if (path == null) {
        throw new FileNotFoundException("No path: " + uri);
    }
    int len = path.size();
    int id;
    if (len == 1) {
        try {
            id = Integer.parseInt(path.get(0));
        } catch (NumberFormatException e) {
            throw new FileNotFoundException("Single path segment is not a resource ID: " + uri);
        }
    } else if (len == 2) {
        id = r.getIdentifier(path.get(1), path.get(0), authority);
    } else {
        throw new FileNotFoundException("More than two path segments: " + uri);
    }
    if (id == 0) {
        throw new FileNotFoundException("No resource found for: " + uri);
    }
    return r.getDrawable(id);
}

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

/**
 * Import of hidden method: ContentResolver.getResourceId(Uri).
 * Modified to return a drawable, rather than a hidden type.
 *//*from   ww w  .  ja v  a  2  s . c om*/
Drawable getDrawableFromResourceUri(Uri uri) throws FileNotFoundException {
    String authority = uri.getAuthority();
    Resources r;
    if (TextUtils.isEmpty(authority)) {
        throw new FileNotFoundException("No authority: " + uri);
    } else {
        try {
            r = mContext.getPackageManager().getResourcesForApplication(authority);
        } catch (NameNotFoundException ex) {
            throw new FileNotFoundException("No package found for authority: " + uri);
        }
    }
    List<String> path = uri.getPathSegments();
    if (path == null) {
        throw new FileNotFoundException("No path: " + uri);
    }
    int len = path.size();
    int id;
    if (len == 1) {
        try {
            id = Integer.parseInt(path.get(0));
        } catch (NumberFormatException e) {
            throw new FileNotFoundException("Single path segment is not a resource ID: " + uri);
        }
    } else if (len == 2) {
        id = r.getIdentifier(path.get(1), path.get(0), authority);
    } else {
        throw new FileNotFoundException("More than two path segments: " + uri);
    }
    if (id == 0) {
        throw new FileNotFoundException("No resource found for: " + uri);
    }
    return r.getDrawable(id);
}

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

/**
 * Updates internal data structures when the user's selection of location providers has changed.
 * @param context/*from w  w w.  java 2 s . co m*/
 */
protected static void updateLocationProviders(Context context) {
    // add overlays
    if (isMapViewReady) {
        Set<String> providers = mSharedPreferences.getStringSet(SettingsActivity.KEY_PREF_LOC_PROV,
                new HashSet<String>(Arrays.asList(
                        new String[] { LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER })));

        updateLocationProviderStyles();

        mapCircles = new HashMap<String, Circle>();
        mapMarkers = new HashMap<String, Marker>();

        ArrayList<String> removedProviders = new ArrayList<String>();
        for (String pr : providerInvalidators.keySet())
            if (!providers.contains(pr))
                removedProviders.add(pr);
        for (String pr : removedProviders)
            providerInvalidators.remove(pr);

        Log.d("MainActivity", "Provider location cache: " + providerLocations.keySet().toString());

        Layers layers = mapMap.getLayerManager().getLayers();

        // remove all layers other than tile render layer from map
        for (int i = 0; i < layers.size();)
            if ((layers.get(i) instanceof TileRendererLayer) || (layers.get(i) instanceof TileDownloadLayer)) {
                i++;
            } else {
                layers.remove(i);
            }

        for (String pr : providers) {
            // no invalidator for GPS, which is invalidated through GPS status
            if ((!pr.equals(LocationManager.GPS_PROVIDER)) && (providerInvalidators.get(pr)) == null) {
                final String provider = pr;
                final Context ctx = context;
                providerInvalidators.put(pr, new Runnable() {
                    private String mProvider = provider;

                    @Override
                    public void run() {
                        if (isMapViewReady) {
                            Location location = providerLocations.get(mProvider);
                            if (location != null)
                                markLocationAsStale(location);
                            applyLocationProviderStyle(ctx, mProvider, LOCATION_PROVIDER_GRAY);
                        }
                    }
                });
            }

            String styleName = assignLocationProviderStyle(pr);
            LatLong latLong;
            float acc;
            boolean visible;
            if ((providerLocations.get(pr) != null) && (providerLocations.get(pr).getProvider() != "")) {
                latLong = new LatLong(providerLocations.get(pr).getLatitude(),
                        providerLocations.get(pr).getLongitude());
                if (providerLocations.get(pr).hasAccuracy())
                    acc = providerLocations.get(pr).getAccuracy();
                else
                    acc = 0;
                visible = true;
                if (isLocationStale(providerLocations.get(pr)))
                    styleName = LOCATION_PROVIDER_GRAY;
                Log.d("MainActivity", pr + " has " + latLong.toString());
            } else {
                latLong = new LatLong(0, 0);
                acc = 0;
                visible = false;
                Log.d("MainActivity", pr + " has no location, hiding");
            }

            // Circle layer
            Resources res = context.getResources();
            TypedArray style = res
                    .obtainTypedArray(res.getIdentifier(styleName, "array", context.getPackageName()));
            Paint fill = AndroidGraphicFactory.INSTANCE.createPaint();
            fill.setColor(style.getColor(STYLE_FILL, R.color.circle_gray_fill));
            fill.setStyle(Style.FILL);
            Paint stroke = AndroidGraphicFactory.INSTANCE.createPaint();
            stroke.setColor(style.getColor(STYLE_STROKE, R.color.circle_gray_stroke));
            stroke.setStrokeWidth(4); // FIXME: make this DPI-dependent
            stroke.setStyle(Style.STROKE);
            Circle circle = new Circle(latLong, acc, fill, stroke);
            mapCircles.put(pr, circle);
            layers.add(circle);
            circle.setVisible(visible);

            // Marker layer
            Drawable drawable = style.getDrawable(STYLE_MARKER);
            Bitmap bitmap = AndroidGraphicFactory.convertToBitmap(drawable);
            Marker marker = new Marker(latLong, bitmap, 0, -bitmap.getHeight() * 9 / 20);
            mapMarkers.put(pr, marker);
            layers.add(marker);
            marker.setVisible(visible);
            style.recycle();
        }

        // move layers into view
        updateMap();
    }
}

From source file:github.why168.swipeback.view.SwipeBackLayout.java

private boolean oldCheckDeviceHasNavigationBar(Activity activity) {
    boolean hasNavigationBar = false;
    Resources resources = activity.getResources();
    int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
    if (id > 0) {
        hasNavigationBar = resources.getBoolean(id);
    }/*from  w  w w .j  a  v a2s .co m*/
    try {
        Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
        Method m = systemPropertiesClass.getMethod("get", String.class);
        String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
        if ("1".equals(navBarOverride)) {
            hasNavigationBar = false;
        } else if ("0".equals(navBarOverride)) {
            hasNavigationBar = true;
        }
    } catch (Exception e) {
    }
    return hasNavigationBar;
}

From source file:github.why168.swipeback.view.SwipeBackLayout.java

/**
 * ??/*from  w w  w .  j a va  2  s.  c o  m*/
 *
 * @param activity
 * @return
 */
public int getNavigationBarHeight(Activity activity) {
    int navigationBarHeight = 0;
    Resources resources = activity.getResources();
    int resourceId = resources
            .getIdentifier(resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT
                    ? "navigation_bar_height"
                    : "navigation_bar_height_landscape", "dimen", "android");
    if (resourceId > 0 && checkDeviceHasNavigationBar(activity)) {
        navigationBarHeight = resources.getDimensionPixelSize(resourceId);
    }
    return navigationBarHeight;
}

From source file:me.piebridge.bible.Bible.java

private void checkApkData() {
    Log.d(TAG, "checking apkdata");
    try {//from w w w.  j av  a  2  s .c  om
        String packageName = mContext.getPackageName();
        PackageManager pm = mContext.getPackageManager();
        SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(mContext);
        ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
        for (String applicationName : pm.getPackagesForUid(ai.uid)) {
            if (packageName.equals(applicationName)) {
                continue;
            }

            // version
            String version = applicationName.replace(packageName + ".", "");

            // resources
            Resources resources = mContext
                    .createPackageContext(applicationName, Context.CONTEXT_IGNORE_SECURITY).getResources();

            // newVersion
            int versionCode = pm.getPackageInfo(applicationName, 0).versionCode;
            boolean newVersion = (preference.getInt(version, 0) != versionCode);

            // resid
            int resid = resources.getIdentifier("a", "raw", applicationName);
            if (resid == 0) {
                resid = resources.getIdentifier("xa", "raw", applicationName);
            }
            if (resid == 0) {
                Log.d(TAG, "package " + applicationName + " has no R.raw.a nor R.raw.xa");
                continue;
            }

            // file
            File file;
            if (versionpaths.containsKey(version)) {
                file = new File(versionpaths.get(version));
            } else {
                file = new File(getExternalFilesDirWrapper(), version + ".sqlite3");
            }
            if (file.exists() && !file.isFile()) {
                file.delete();
            }

            boolean unpack = unpackRaw(resources, newVersion, resid, file);
            if (newVersion && unpack) {
                preference.edit().putInt(version, versionCode).commit();
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "", e);
    }
}