Example usage for android.app Activity getResources

List of usage examples for android.app Activity getResources

Introduction

In this page you can find the example usage for android.app Activity getResources.

Prototype

@Override
    public Resources getResources() 

Source Link

Usage

From source file:com.example.ray.firstapp.bottombar.BottomBar.java

private static void navBarMagic(Activity activity, final BottomBar bottomBar) {
    Resources res = activity.getResources();
    int softMenuIdentifier = res.getIdentifier("config_showNavigationBar", "bool", "android");
    int navBarIdentifier = res.getIdentifier("navigation_bar_height", "dimen", "android");
    int navBarHeight = 0;

    if (navBarIdentifier > 0) {
        navBarHeight = res.getDimensionPixelSize(navBarIdentifier);
    }//from  w  w  w . j  ava2 s.c o  m

    if (!bottomBar.drawBehindNavBar() || navBarHeight == 0
            || (!(softMenuIdentifier > 0 && res.getBoolean(softMenuIdentifier)))) {
        return;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH
            && ViewConfiguration.get(activity).hasPermanentMenuKey()) {
        return;
    }

    /**
     * Copy-paste coding made possible by:
     * http://stackoverflow.com/a/14871974/940036
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Display d = activity.getWindowManager().getDefaultDisplay();

        DisplayMetrics realDisplayMetrics = new DisplayMetrics();
        d.getRealMetrics(realDisplayMetrics);

        int realHeight = realDisplayMetrics.heightPixels;
        int realWidth = realDisplayMetrics.widthPixels;

        DisplayMetrics displayMetrics = new DisplayMetrics();
        d.getMetrics(displayMetrics);

        int displayHeight = displayMetrics.heightPixels;
        int displayWidth = displayMetrics.widthPixels;

        boolean hasSoftwareKeys = (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0;

        if (!hasSoftwareKeys) {
            return;
        }
    }
    /**
     * End of delicious copy-paste code
     */

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
            && res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        activity.getWindow().getAttributes().flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;

        if (bottomBar.useTopOffset()) {
            int offset;
            int statusBarResource = res.getIdentifier("status_bar_height", "dimen", "android");

            if (statusBarResource > 0) {
                offset = res.getDimensionPixelSize(statusBarResource);
            } else {
                offset = MiscUtils.dpToPixel(activity, 25);
            }

            if (!bottomBar.useOnlyStatusbarOffset()) {
                TypedValue tv = new TypedValue();
                if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
                    offset += TypedValue.complexToDimensionPixelSize(tv.data, res.getDisplayMetrics());
                } else {
                    offset += MiscUtils.dpToPixel(activity, 56);
                }
            }

            bottomBar.getUserContainer().setPadding(0, offset, 0, 0);
        }

        final View outerContainer = bottomBar.getOuterContainer();
        final int navBarHeightCopy = navBarHeight;
        bottomBar.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @SuppressWarnings("deprecation")
                    @Override
                    public void onGlobalLayout() {
                        bottomBar.shyHeightAlreadyCalculated();

                        int newHeight = outerContainer.getHeight() + navBarHeightCopy;
                        outerContainer.getLayoutParams().height = newHeight;

                        if (bottomBar.isShy()) {
                            int defaultOffset = bottomBar.useExtraOffset() ? navBarHeightCopy : 0;
                            bottomBar.setTranslationY(defaultOffset);
                            ((CoordinatorLayout.LayoutParams) bottomBar.getLayoutParams())
                                    .setBehavior(new BottomNavigationBehavior(newHeight, defaultOffset));
                        }

                        ViewTreeObserver obs = outerContainer.getViewTreeObserver();

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            obs.removeOnGlobalLayoutListener(this);
                        } else {
                            obs.removeGlobalOnLayoutListener(this);
                        }
                    }
                });
    }
}

From source file:com.ecml.FileUri.java

/** Return the file contents as a byte array.
 *  If any IO error occurs, return null.
 *///from   w  w w .j av  a  2 s.c o m
public byte[] getData(Activity activity) {
    try {
        byte[] data;
        int totallen, len, offset;

        // First, determine the file length
        data = new byte[4096];
        InputStream file;
        String uriString = uri.toString();
        if (uriString.startsWith("file:///android_asset/")) {
            AssetManager asset = activity.getResources().getAssets();
            String filepath = uriString.replace("file:///android_asset/", "");
            file = asset.open(filepath);
        } else if (uriString.startsWith("content://")) {
            ContentResolver resolver = activity.getContentResolver();
            file = resolver.openInputStream(uri);
        } else {
            file = new FileInputStream(uri.getPath());
        }
        totallen = 0;
        len = file.read(data, 0, 4096);
        while (len > 0) {
            totallen += len;
            len = file.read(data, 0, 4096);
        }
        file.close();

        // Now read in the data
        offset = 0;
        data = new byte[totallen];

        if (uriString.startsWith("file:///android_asset/")) {
            AssetManager asset = activity.getResources().getAssets();
            String filepath = uriString.replace("file:///android_asset/", "");
            file = asset.open(filepath);
        } else if (uriString.startsWith("content://")) {
            ContentResolver resolver = activity.getContentResolver();
            file = resolver.openInputStream(uri);
        } else {
            file = new FileInputStream(uri.getPath());
        }
        while (offset < totallen) {
            len = file.read(data, offset, totallen - offset);
            if (len <= 0) {
                throw new MidiFileException("Error reading midi file", offset);
            }
            offset += len;
        }
        return data;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.bt.heliniumstudentapp.MainActivity.java

protected static void setStatusBar(Activity context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        context.getWindow().setStatusBarColor(Color.TRANSPARENT);

        if (context == mainContext)
            drawerDL.setStatusBarBackgroundColor(ContextCompat.getColor(context, darkPrimaryColor));
        else//w ww.  j  a  v a2s  .c o m
            context.getWindow().setStatusBarColor(ContextCompat.getColor(context, darkPrimaryColor));

        context.setTaskDescription(new ActivityManager.TaskDescription(context.getString(R.string.app_name),
                BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher),
                ContextCompat.getColor(context, primaryColor)));

    }
}

From source file:com.higgses.griffin.annotation.app.GinInjector.java

/**
 * ??//from w w w . java 2  s. c om
 * 
 * @param object
 * @param field
 */
private void injectResource(Object object, Field field) {
    if (field.isAnnotationPresent(GinInjectResource.class)) {
        GinInjectResource resourceJect = field.getAnnotation(GinInjectResource.class);
        int resourceID = resourceJect.id();
        try {
            Activity activity = null;
            if (object instanceof Activity) {
                activity = (Activity) object;
            } else if (object instanceof Fragment) {
                activity = ((Fragment) object).getActivity();
            }
            field.setAccessible(true);
            Resources resources = activity.getResources();
            String type = resources.getResourceTypeName(resourceID);
            if (type.equalsIgnoreCase("string")) {
                field.set(activity, activity.getResources().getString(resourceID));
            } else if (type.equalsIgnoreCase("drawable")) {
                field.set(activity, activity.getResources().getDrawable(resourceID));
            } else if (type.equalsIgnoreCase("layout")) {
                field.set(activity, activity.getResources().getLayout(resourceID));
            } else if (type.equalsIgnoreCase("array")) {
                if (field.getType().equals(int[].class)) {
                    field.set(activity, activity.getResources().getIntArray(resourceID));
                } else if (field.getType().equals(String[].class)) {
                    field.set(activity, activity.getResources().getStringArray(resourceID));
                } else {
                    field.set(activity, activity.getResources().getStringArray(resourceID));
                }

            } else if (type.equalsIgnoreCase("color")) {
                if (field.getType().equals(Integer.TYPE)) {
                    field.set(activity, activity.getResources().getColor(resourceID));
                } else {
                    field.set(activity, activity.getResources().getColorStateList(resourceID));
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:es.usc.citius.servando.calendula.fragments.HomeProfileMgr.java

public void init(View view, final Activity ctx) {
    this.context = ctx;
    this.rootView = view;

    //        Animation in = AnimationUtils.loadAnimation(ctx, android.R.anim.fade_in);
    //        Animation out = AnimationUtils.loadAnimation(ctx, android.R.anim.fade_out);
    moods = ctx.getResources().getStringArray(R.array.moods);
    monthTv = (TextView) view.findViewById(R.id.month_text);
    dayTv = (TextView) view.findViewById(R.id.day_text);
    //clock = (CustomDigitalClock) view.findViewById(R.id.home_clock);
    bottomShadow = (ImageView) view.findViewById(R.id.bottom_shadow);
    profileInfo = view.findViewById(R.id.profile_info);

    profileUsername = (TextView) view.findViewById(R.id.profile_username);
    profileContainer = (RelativeLayout) view.findViewById(R.id.profile_container);
    profileImageContainer = view.findViewById(R.id.profile_image_container);
    background = (ImageView) view.findViewById(R.id.image_switcher);

    modFabButton = (RoundedImageView) view.findViewById(R.id.mod_circle);
    moodImg = (ImageView) view.findViewById(R.id.mood_button);
    moodImg.setOnClickListener(new View.OnClickListener() {
        @Override//from  w w w  . j  a  va2 s  .c  o  m
        public void onClick(View v) {
            showMoodsDialog();
        }
    });

    background.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            updateBackground();
        }
    });

    updateModButton();
    updateProfileInfo();

    profileInfo.setVisibility(View.INVISIBLE);
    background.setVisibility(View.INVISIBLE);
    bottomShadow.setVisibility(View.INVISIBLE);

    Picasso.with(context).load("file:///android_asset/" + getBackgroundPath(ctx)).into(background);

    background.post(new Runnable() {
        @Override
        public void run() {
            bottomShadow.setVisibility(View.VISIBLE);
            background.setVisibility(View.VISIBLE);
            background.animate().alpha(1).setDuration(200);
        }
    });

    background.postDelayed(new Runnable() {
        @Override
        public void run() {
            profileInfo.setVisibility(View.VISIBLE);
            profileInfo.setAlpha(0);
            profileInfo.animate().alpha(1).setDuration(400);
        }
    }, 300);

}

From source file:ch.uzh.supersede.feedbacklibrary.utils.Utils.java

private static void startActivity(@NonNull final Activity activity, @NonNull final Intent intent,
        @NonNull String baseURL, final boolean isCapturingScreenshot) {
    Retrofit rtf = new Retrofit.Builder().baseUrl(baseURL).addConverterFactory(GsonConverterFactory.create())
            .build();/*  ww w .j a va 2 s.  c  o  m*/
    feedbackAPI fbAPI = rtf.create(feedbackAPI.class);
    Call<ResponseBody> checkUpAndRunning = fbAPI.pingOrchestrator();

    if (checkUpAndRunning != null) {
        checkUpAndRunning.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e(TAG, "Failed to ping the server. onFailure method called", t);
                DialogUtils.showInformationDialog(activity,
                        new String[] { activity.getResources().getString(
                                R.string.supersede_feedbacklibrary_feedback_application_unavailable_text) },
                        true);
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.code() == 200) {
                    if (isCapturingScreenshot) {
                        String defaultImagePath = captureScreenshot(activity);
                        intent.putExtra(FeedbackActivity.DEFAULT_IMAGE_PATH, defaultImagePath);
                    }
                    activity.startActivity(intent);
                } else {
                    Log.e(TAG, "The server is not up and running. Response code == " + response.code());
                    DialogUtils.showInformationDialog(activity,
                            new String[] { activity.getResources().getString(
                                    R.string.supersede_feedbacklibrary_feedback_application_unavailable_text) },
                            true);
                }
            }
        });
    } else {
        Log.e(TAG, "Failed to ping the server. Call<ResponseBody> checkUpAndRunning result is null");
        DialogUtils.showInformationDialog(activity,
                new String[] { activity.getResources()
                        .getString(R.string.supersede_feedbacklibrary_feedback_application_unavailable_text) },
                true);
    }
}

From source file:com.esminis.server.library.activity.main.MainViewImpl.java

@Override
public boolean createMenu(MenuInflater inflater, Menu menu) {
    inflater.inflate(R.menu.main, menu);
    final Activity activity = this.activity.get();
    if (activity != null) {
        menu.findItem(R.id.menu_about).setIcon(new InsetDrawable(
                VectorDrawableCompat.create(activity.getResources(), R.drawable.ic_info, null), 0));
    }//from   ww w. j a va 2 s  .  com
    return true;
}

From source file:com.harlan.jxust.ui.view.bottombar.BottomBar.java

private static void navBarMagic(Activity activity, final BottomBar bottomBar) {
    Resources res = activity.getResources();
    int softMenuIdentifier = res.getIdentifier("config_showNavigationBar", "bool", "android");
    int navBarIdentifier = res.getIdentifier("navigation_bar_height", "dimen", "android");
    int navBarHeight = 0;

    if (navBarIdentifier > 0) {
        navBarHeight = res.getDimensionPixelSize(navBarIdentifier);
    }/*from ww  w.  j  a  va2  s. c  o m*/

    if (!bottomBar.drawBehindNavBar() || navBarHeight == 0
            || (!(softMenuIdentifier > 0 && res.getBoolean(softMenuIdentifier)))) {
        return;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH
            && ViewConfiguration.get(activity).hasPermanentMenuKey()) {
        return;
    }

    /**
     * Copy-paste coding made possible by:
     * http://stackoverflow.com/a/14871974/940036
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Display d = activity.getWindowManager().getDefaultDisplay();

        DisplayMetrics realDisplayMetrics = new DisplayMetrics();
        d.getRealMetrics(realDisplayMetrics);

        int realHeight = realDisplayMetrics.heightPixels;
        int realWidth = realDisplayMetrics.widthPixels;

        DisplayMetrics displayMetrics = new DisplayMetrics();
        d.getMetrics(displayMetrics);

        int displayHeight = displayMetrics.heightPixels;
        int displayWidth = displayMetrics.widthPixels;

        boolean hasSoftwareKeys = (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0;

        if (!hasSoftwareKeys) {
            return;
        }
    }
    /**
     * End of delicious copy-paste code
     */

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
            && res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        activity.getWindow().getAttributes().flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;

        if (bottomBar.useTopOffset()) {
            int offset;
            int statusBarResource = res.getIdentifier("status_bar_height", "dimen", "android");

            if (statusBarResource > 0) {
                offset = res.getDimensionPixelSize(statusBarResource);
            } else {
                offset = MiscUtils.dpToPixel(activity, 25);
            }

            if (!bottomBar.useOnlyStatusbarOffset()) {
                TypedValue tv = new TypedValue();
                if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
                    offset += TypedValue.complexToDimensionPixelSize(tv.data, res.getDisplayMetrics());
                } else {
                    offset += MiscUtils.dpToPixel(activity, 56);
                }
            }

            bottomBar.getUserContainer().setPadding(0, offset, 0, 0);
        }

        final View outerContainer = bottomBar.getOuterContainer();
        final int navBarHeightCopy = navBarHeight;
        bottomBar.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @SuppressWarnings("deprecation")
                    @Override
                    public void onGlobalLayout() {
                        bottomBar.shyHeightAlreadyCalculated();

                        int newHeight = outerContainer.getHeight() + navBarHeightCopy;
                        outerContainer.getLayoutParams().height = newHeight;

                        if (bottomBar.isShy()) {
                            int defaultOffset = bottomBar.useExtraOffset() ? navBarHeightCopy : 0;
                            bottomBar.setTranslationY(defaultOffset);
                            ((CoordinatorLayout.LayoutParams) bottomBar.getLayoutParams())
                                    .setBehavior(new BottomNavigationBehavior(newHeight, defaultOffset,
                                            bottomBar.isShy(), bottomBar.mIsTabletMode));
                        }

                        ViewTreeObserver obs = outerContainer.getViewTreeObserver();

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            obs.removeOnGlobalLayoutListener(this);
                        } else {
                            obs.removeGlobalOnLayoutListener(this);
                        }
                    }
                });
    }
}

From source file:de.k3b.android.androFotoFinder.imagedetail.ImagePagerAdapterFromCursor.java

public ImagePagerAdapterFromCursor(final Activity context, QueryParameterParcelable parameters, String name) {
    mActivity = context;//from ww w .j  av  a  2  s.  c  o m
    debugPrefix = "ImagePagerAdapterFromCursor#" + (id++) + "@" + name + " ";
    Global.debugMemory(debugPrefix, "ctor");
    mMaxTitleLength = context.getResources().getInteger(R.integer.title_length_in_chars);

    if (Global.debugEnabled) {
        Log.i(Global.LOG_CONTEXT, debugPrefix + "()");
    }

    if (parameters != null) {
        requery(context, parameters);
    }
}

From source file:com.mercandalli.android.apps.files.file.local.FileLocalFragment.java

private void initViews() {
    mProgressBar.setVisibility(View.INVISIBLE);
    mRecyclerView.setHasFixedSize(true);
    mSwipeRefreshLayout.setEnabled(true);
    mSwipeRefreshLayout.setOnRefreshListener(this);
    mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
            android.R.color.holo_green_light, android.R.color.holo_orange_light,
            android.R.color.holo_red_light);

    final Activity activity = getActivity();
    final int nbColumn = activity.getResources().getInteger(R.integer.column_number_card);
    if (nbColumn <= 1) {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
    } else {//from   www .j  a v a 2  s .  c om
        mRecyclerView.setLayoutManager(new GridLayoutManager(activity, nbColumn));
    }

    mFileModelAdapter = new FileModelAdapter(getContext(), mFilesList, this, this, this);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mScaleAnimationAdapter = new ScaleAnimationAdapter(mRecyclerView, mFileModelAdapter);
        mScaleAnimationAdapter.setDuration(220);
        mScaleAnimationAdapter.setOffsetDuration(32);
        mRecyclerView.setAdapter(mScaleAnimationAdapter);
    } else {
        mRecyclerView.setAdapter(mFileModelAdapter);
    }

    mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (dy <= 0) {
                if (!mIsFabAnimating) {
                    mIsFabAnimating = true;
                    mIsFabHidden = false;
                    mFileLocalFabManager.updateFabButtons();
                    mHandler.removeCallbacks(mRunnable);
                    mHandler.postDelayed(mRunnable, 250);
                }
            } else {
                if (!mIsFabAnimating) {
                    mIsFabAnimating = true;
                    mIsFabHidden = true;
                    mFileLocalFabManager.updateFabButtons();
                    mHandler.removeCallbacks(mRunnable);
                    mHandler.postDelayed(mRunnable, 250);
                }
            }
        }
    });
}