Example usage for android.content.res Resources obtainTypedArray

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

Introduction

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

Prototype

@NonNull
public TypedArray obtainTypedArray(@ArrayRes int id) throws NotFoundException 

Source Link

Document

Return an array of heterogeneous values.

Usage

From source file:android.support.wear.widget.CircularProgressLayout.java

private int[] getColorListFromResources(Resources resources, int arrayResId) {
    TypedArray colorArray = resources.obtainTypedArray(arrayResId);
    int[] colors = new int[colorArray.length()];
    for (int i = 0; i < colorArray.length(); i++) {
        colors[i] = colorArray.getColor(i, 0);
    }//from   w w w  .  ja va2  s .  c o m
    colorArray.recycle();
    return colors;
}

From source file:com.mikecorrigan.trainscorekeeper.Players.java

@SuppressLint("NewApi")
public Players(final Activity context, ViewGroup viewGroup, final JSONArray jsonPlayers) {
    Log.vc(VERBOSE, TAG,/*from w  w  w .  j a va2 s  . co m*/
            "ctor: context=" + context + ", viewGroup=" + viewGroup + ", jsonPlayers=" + jsonPlayers);

    viewGroup.removeAllViews();

    Resources resources = context.getResources();

    String[] playerNames = resources.getStringArray(R.array.playerNames);

    TypedArray drawablesArray = resources.obtainTypedArray(R.array.playerDrawables);

    TypedArray colorIdsArray = resources.obtainTypedArray(R.array.playerTextColors);
    int[] colorIds = new int[colorIdsArray.length()];
    for (int i = 0; i < colorIdsArray.length(); i++) {
        colorIds[i] = colorIdsArray.getResourceId(i, -1);
    }

    listeners = new HashSet<Listener>();
    players = new SparseArray<Player>();

    for (int i = 0; i < playerNames.length; i++) {
        PlayerButton toggleButton = new PlayerButton(context);
        toggleButton.setPlayerId(i);
        LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, 1f);
        toggleButton.setLayoutParams(layoutParams);
        Drawable drawable = drawablesArray.getDrawable(i);
        int sdk = android.os.Build.VERSION.SDK_INT;
        if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
            toggleButton.setBackgroundDrawable(drawable);
        } else {
            toggleButton.setBackground(drawable);
        }
        toggleButton.setPadding(10, 10, 10, 10);
        toggleButton.setTextColor(resources.getColor(colorIds[i]));
        toggleButton.setOnClickListener(onSelect);

        viewGroup.addView(toggleButton);

        final String name = playerNames[i];

        boolean enabled = true;

        // If the players configuration is available, determine which players are enabled.
        if (jsonPlayers != null) {
            enabled = false;
            for (int j = 0; j < jsonPlayers.length(); j++) {
                String jsonName = jsonPlayers.optString(j, "");
                if (jsonName.equalsIgnoreCase(name)) {
                    enabled = true;
                    break;
                }
            }
        }

        Player player = new Player(toggleButton, i, name, enabled);
        players.put(i, player);
    }

    setSelection(-1);

    drawablesArray.recycle();
    colorIdsArray.recycle();
}

From source file:com.google.android.apps.santatracker.village.Village.java

public int[] getIntArray(Resources resources, int resId) {
    TypedArray array = resources.obtainTypedArray(resId);
    int[] rc = new int[array.length()];
    TypedValue value = new TypedValue();
    for (int i = 0; i < array.length(); i++) {
        array.getValue(i, value);//from   w w  w  . ja va 2  s  .com
        rc[i] = value.resourceId;
    }
    array.recycle();
    return rc;
}

From source file:com.example.alvarpao.popularmovies.MovieGridFragment.java

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.main_fragment, menu);

    // Get the array of values for the sort options since the onItemSelected method only
    // returns the string representation of the item, not the value associated
    Resources resources = getResources();
    final TypedArray sortArrayValues = resources.obtainTypedArray(R.array.sort_options_values);

    MenuItem sortMenuItem = menu.findItem(R.id.sort_spinner);
    mSortSpinner = (Spinner) MenuItemCompat.getActionView(sortMenuItem);
    mSortSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override//  w  w  w  .  j  a  va2 s. c  o m
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            if (Utility.getPreferredSortOptionPosition(getActivity()) != position) {
                // Update the shared preferences with the new sort option election
                SharedPreferences sharedPreferences = PreferenceManager
                        .getDefaultSharedPreferences(getActivity());
                SharedPreferences.Editor editor = sharedPreferences.edit();
                //Save the sort_by value to query the movie database
                editor.putString(getString(R.string.sort_preference_key), sortArrayValues.getString(position));
                // Save the current position of the selected sort option
                editor.putInt(getString(R.string.sort_position_preference_key), position);
                editor.commit();

                // Update movie grid to reflect new sort option selected by user
                resetMovieGrid();
                getMovies(PAGE_1);
            }

            else {
                // If the sort option didn't change, the event most likely was triggered by
                // either a rotation or the activity being created. In case of the rotation
                // the state has already been restored in the onCreate() method, after onCreate()
                // the onCreateOptionsMenu() is called. If the activity has been created, the
                // favorite movies need to be fetched
                if (Utility.getPreferredSortOption(getActivity())
                        .equals(getString(R.string.sort_favorites_value))) {
                    if (!mMovies.isEmpty() && ((MainActivity) getActivity()).inTwoPaneLayout())
                        updateDetailsFragment();
                    else if (mMovies.isEmpty())
                        getMovies(Integer.valueOf(mPageToFetch).toString());
                }

                else {
                    // For the other sort options since pagination is involved the default
                    // movie to display in the details fragment when the user hasn't selected
                    // any movie is either the first one in the returned list when it is
                    // first loaded or the first visible movie before rotation. The first one
                    // when is first loaded is instantiated in the onScroll method
                    if (((MainActivity) getActivity()).inTwoPaneLayout()) {
                        if ((mSelectedMovie != -1) && (mMovieAdapter.getCount() != 0)) {
                            Movie selectedMovie = mMovieAdapter.getItem(mSelectedMovie);
                            ((Callback) getActivity()).onItemSelected(selectedMovie);
                        }
                    }
                    // Determine if another page needs to be retrieved by making an API call
                    getMovies(Integer.valueOf(mPageToFetch).toString());
                }

                // Restoring the scroll position
                mMoviesGridView.smoothScrollToPosition(mCurrentScrollPosition);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            //Do nothing
        }
    });

    // This statement is needed to restore the state of the sort selection in case a screen
    // rotation has occurred. The spinner is restored to the position it was retrieved
    // from the SharedPreferences;
    mSortSpinner.setSelection(Utility.getPreferredSortOptionPosition(getActivity()));
}

From source file:com.mikecorrigan.trainscorekeeper.FragmentSummary.java

@SuppressLint("NewApi")
@Override//w  ww .  java  2  s . c om
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.vc(VERBOSE, TAG, "onCreateView: inflater=" + inflater + ", container=" + container
            + ", savedInstanceState=" + Utils.bundleToString(savedInstanceState));

    View rootView = inflater.inflate(R.layout.fragment_summary, container, false);

    final MainActivity activity = (MainActivity) getActivity();
    final Context context = activity;
    final Resources resources = context.getResources();

    // Get the model and attach a listener.
    game = activity.getGame();
    if (game != null) {
        game.addListener(mGameListener);
    }

    players = activity.getPlayers();

    // Get resources.
    String[] playerNames = resources.getStringArray(R.array.playerNames);

    TypedArray drawablesArray = resources.obtainTypedArray(R.array.playerDrawables);

    TypedArray playerTextColorsArray = resources.obtainTypedArray(R.array.playerTextColors);
    int[] playerTextColorsIds = new int[playerTextColorsArray.length()];
    for (int i = 0; i < playerTextColorsArray.length(); i++) {
        playerTextColorsIds[i] = playerTextColorsArray.getResourceId(i, -1);
    }

    // Get root view.
    ScrollView scrollView = (ScrollView) rootView.findViewById(R.id.scroll_view);

    // Create table.
    tableLayout = new TableLayout(context);
    TableLayout.LayoutParams tableLayoutParams = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT);
    tableLayout.setLayoutParams(tableLayoutParams);
    scrollView.addView(tableLayout);

    // Add header.
    {
        TableRow row = new TableRow(context);
        row.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        tableLayout.addView(row);

        TextView tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setPadding(10, 10, 10, 10);
        tv.setText(resources.getString(R.string.player));
        tv.setTypeface(null, Typeface.BOLD);
        row.addView(tv);

        tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setPadding(10, 10, 10, 10);
        tv.setText(resources.getString(R.string.trains));
        tv.setTypeface(null, Typeface.BOLD);
        row.addView(tv);

        tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setPadding(10, 10, 10, 10);
        tv.setText(resources.getString(R.string.contracts));
        tv.setTypeface(null, Typeface.BOLD);
        row.addView(tv);

        tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setPadding(10, 10, 10, 10);
        tv.setText(resources.getString(R.string.bonuses));
        tv.setTypeface(null, Typeface.BOLD);
        row.addView(tv);

    }

    // Add rows.
    for (int i = 0; i < players.getNum(); i++) {
        TableRow row = new TableRow(context);
        row.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        tableLayout.addView(row);

        ToggleButton toggleButton = new ToggleButton(context);
        toggleButton.setGravity(Gravity.CENTER);
        toggleButton.setPadding(10, 10, 10, 10);
        toggleButton.setText(playerNames[i]);
        toggleButton.setClickable(false);
        Drawable drawable = drawablesArray.getDrawable(i);
        int sdk = android.os.Build.VERSION.SDK_INT;
        if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
            toggleButton.setBackgroundDrawable(drawable);
        } else {
            toggleButton.setBackground(drawable);
        }
        toggleButton.setTextColor(resources.getColor(playerTextColorsIds[i]));
        row.addView(toggleButton);

        TextView tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setPadding(10, 10, 10, 10);
        row.addView(tv);

        tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setPadding(10, 10, 10, 10);
        row.addView(tv);

        tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setPadding(10, 10, 10, 10);
        row.addView(tv);

    }

    Bundle args = getArguments();
    if (args == null) {
        Log.e(TAG, "onCreateView: missing arguments");
        return rootView;
    }

    drawablesArray.recycle();
    playerTextColorsArray.recycle();

    // final int index = args.getInt(ARG_INDEX);
    // final String tabSpec = args.getString(ARG_TAB_SPEC);

    return rootView;
}

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

/**
 * Applies a style to the map overlays associated with a given location provider.
 * //from  w ww. j av  a  2s  .c o 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 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:org.gnucash.android.ui.account.AccountFormFragment.java

/**
 * Returns an array of colors used for accounts.
 * The array returned has the actual color values and not the resource ID.
 * @return Integer array of colors used for accounts
 */// w w  w .  j a  v  a  2s  .  co m
private int[] getAccountColorOptions() {
    Resources res = getResources();
    TypedArray colorTypedArray = res.obtainTypedArray(R.array.account_colors);
    int[] colorOptions = new int[colorTypedArray.length()];
    for (int i = 0; i < colorTypedArray.length(); i++) {
        int color = colorTypedArray.getColor(i, R.color.title_green);
        colorOptions[i] = color;
    }
    return colorOptions;
}

From source file:com.microsoft.mimickeralarm.mimics.MimicColorCaptureFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = super.onCreateView(inflater, container, savedInstanceState);

    Resources resources = getResources();

    String subscriptionKey = KeyUtilities.getToken(getActivity(), "vision");
    mVisionServiceRestClient = new VisionServiceRestClient(subscriptionKey);

    String[] questions = resources.getStringArray(R.array.vision_color_questions);
    TextView instruction = (TextView) view.findViewById(R.id.instruction_text);
    mQuestionColorName = questions[new Random().nextInt(questions.length)];
    instruction.setText(String.format(resources.getString(R.string.mimic_vision_prompt), mQuestionColorName));

    TypedArray colorCodeLower = resources.obtainTypedArray(resources
            .getIdentifier(mQuestionColorName + "_range_lower", "array", getActivity().getPackageName()));
    mQuestionColorRangeLower = new float[] { colorCodeLower.getFloat(0, 0f), colorCodeLower.getFloat(1, 0f),
            colorCodeLower.getFloat(2, 0f) };
    colorCodeLower.recycle();/* w w  w. jav a  2 s .  com*/
    TypedArray colorCodeUpper = resources.obtainTypedArray(resources
            .getIdentifier(mQuestionColorName + "_range_upper", "array", getActivity().getPackageName()));
    mQuestionColorRangeUpper = new float[] { colorCodeUpper.getFloat(0, 0f), colorCodeUpper.getFloat(1, 0f),
            colorCodeUpper.getFloat(2, 0f) };
    colorCodeUpper.recycle();

    Logger.init(getActivity());
    Loggable playGameEvent = new Loggable.UserAction(Loggable.Key.ACTION_GAME_COLOR);
    Logger.track(playGameEvent);

    return view;
}

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

/**
 * Updates internal data structures when the user's selection of location providers has changed.
 * @param providers The new set of location providers
 *///from  w w w.  j  a v  a 2  s. c  om
public void onLocationProvidersChanged(Set<String> providers) {
    Context context = this.getContext();
    List<String> allProviders = mainActivity.locationManager.getAllProviders();
    ArrayList<String> removedProviders = new ArrayList<String>();

    for (String pr : providerLocations.keySet())
        if (!providers.contains(pr))
            removedProviders.add(pr);

    // remove cached locations and invalidators for providers which are no longer selected
    for (String pr : removedProviders) {
        providerLocations.remove(pr);
        providerInvalidators.remove(pr);
    }

    // ensure there is a cached location for each chosen provider (can be null)
    for (String pr : providers) {
        if ((allProviders.indexOf(pr) >= 0) && !providerLocations.containsKey(pr)) {
            Location location = new Location("");
            providerLocations.put(pr, location);
        }
    }

    // add overlays
    updateLocationProviderStyles();

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

    Log.d(TAG, "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() {
                    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();
        float density = context.getResources().getDisplayMetrics().density;
        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(Math.max(1.5f * density, 1));
        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:com.vonglasow.michael.satstat.ui.MapSectionFragment.java

/**
 * Applies a style to the map overlays associated with a given location provider.
 * //  w w  w . j  a  va  2 s .com
 * 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 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(Const.STYLE_FILL, R.color.circle_gray_fill));
        circle.getPaintStroke().setColor(style.getColor(Const.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(Const.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();
}