Example usage for android.support.v4.content ContextCompat getDrawable

List of usage examples for android.support.v4.content ContextCompat getDrawable

Introduction

In this page you can find the example usage for android.support.v4.content ContextCompat getDrawable.

Prototype

public static final Drawable getDrawable(Context context, int i) 

Source Link

Usage

From source file:com.justwayward.reader.ui.activity.BookDetailActivity.java

private void initCollection(boolean coll) {
    if (coll) {/*from   ww  w .java 2 s .co  m*/
        mBtnJoinCollection.setText(R.string.book_detail_join_collection);
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.book_detail_info_add_img);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        mBtnJoinCollection.setBackgroundDrawable(
                ContextCompat.getDrawable(this, R.drawable.shape_common_btn_solid_normal));
        mBtnJoinCollection.setCompoundDrawables(drawable, null, null, null);
        mBtnJoinCollection.postInvalidate();
        isJoinedCollections = false;
    } else {
        mBtnJoinCollection.setText(R.string.book_detail_remove_collection);
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.book_detail_info_del_img);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        mBtnJoinCollection
                .setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.btn_join_collection_pressed));
        mBtnJoinCollection.setCompoundDrawables(drawable, null, null, null);
        mBtnJoinCollection.postInvalidate();
        isJoinedCollections = true;
    }
}

From source file:co.ceryle.segmentedbutton.SegmentedButton.java

/**
 * If button has any drawable, it sets drawable's tint color without changing drawable's position.
 *
 * @param drawableId is used to get drawable object
 * @param position   specifies button's drawable position relative to text position.
 *                   These values can be given to position:
 *                   {@link #DRAWABLE_LEFT} sets drawable to the left of button's text
 *                   {@link #DRAWABLE_TOP} sets drawable to the top of button's text
 *                   {@link #DRAWABLE_RIGHT} sets drawable to the right of button's text
 *                   {@link #DRAWABLE_BOTTOM} sets drawable to the bottom of button's text
 * @param color      is used to set drawable's tint color
 *//*from  www .j ava  2  s.c  o  m*/
public void setDrawableTint(int drawableId, int position, int color) {
    Drawable drawable = ContextCompat.getDrawable(context, drawableId);
    setDrawableTint(drawable, position, color);
}

From source file:com.hmatalonga.greenhub.ui.TaskListActivity.java

/**
 * This is the standard support library way of implementing "swipe to delete" feature. You can do custom drawing in onChildDraw method
 * but whatever you draw will disappear once the swipe is over, and while the items are animating to their new position the recycler view
 * background will be visible. That is rarely an desired effect.
 *///ww  w  . j av  a  2s. c  o m
private void setUpItemTouchHelper() {
    ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0,
            ItemTouchHelper.LEFT) {

        // we want to cache these and not allocate anything repeatedly in the onChildDraw method
        Drawable background;
        Drawable xMark;
        int xMarkMargin;
        boolean initiated;

        private void init() {
            background = new ColorDrawable(Color.DKGRAY);
            xMark = ContextCompat.getDrawable(TaskListActivity.this, R.drawable.ic_delete_white_24dp);
            xMark.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
            xMarkMargin = (int) TaskListActivity.this.getResources().getDimension(R.dimen.fab_margin);
            initiated = true;
        }

        // not important, we don't want drag & drop
        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int position = viewHolder.getAdapterPosition();
            TaskAdapter testAdapter = (TaskAdapter) recyclerView.getAdapter();
            if (testAdapter.isUndoOn() && testAdapter.isPendingRemoval(position)) {
                return 0;
            }
            return super.getSwipeDirs(recyclerView, viewHolder);
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
            int swipedPosition = viewHolder.getAdapterPosition();
            TaskAdapter adapter = (TaskAdapter) mRecyclerView.getAdapter();
            boolean undoOn = adapter.isUndoOn();
            if (undoOn) {
                adapter.pendingRemoval(swipedPosition);
            } else {
                adapter.remove(swipedPosition);
            }
        }

        @Override
        public void onChildDraw(Canvas canvas, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                float dX, float dY, int actionState, boolean isCurrentlyActive) {

            View itemView = viewHolder.itemView;

            // not sure why, but this method get's called for viewholder that are already swiped away
            if (viewHolder.getAdapterPosition() == -1) {
                // not interested in those
                return;
            }

            if (!initiated) {
                init();
            }

            // draw background
            background.setBounds(itemView.getRight() + (int) dX, itemView.getTop(), itemView.getRight(),
                    itemView.getBottom());
            background.draw(canvas);

            // draw x mark
            int itemHeight = itemView.getBottom() - itemView.getTop();
            int intrinsicWidth = xMark.getIntrinsicWidth();
            int intrinsicHeight = xMark.getIntrinsicWidth();

            int xMarkLeft = itemView.getRight() - xMarkMargin - intrinsicWidth;
            int xMarkRight = itemView.getRight() - xMarkMargin;
            int xMarkTop = itemView.getTop() + (itemHeight - intrinsicHeight) / 2;
            int xMarkBottom = xMarkTop + intrinsicHeight;
            xMark.setBounds(xMarkLeft, xMarkTop, xMarkRight, xMarkBottom);

            xMark.draw(canvas);

            super.onChildDraw(canvas, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
        }

    };
    ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
    mItemTouchHelper.attachToRecyclerView(mRecyclerView);
}

From source file:com.folioreader.ui.folio.activity.FolioActivity.java

private void initActionBar() {

    appBarLayout = findViewById(R.id.appBarLayout);
    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from   w w  w  .jav a  2  s.c  o  m*/
    actionBar = getSupportActionBar();

    Config config = AppUtil.getSavedConfig(getApplicationContext());
    assert config != null;

    Drawable drawable = ContextCompat.getDrawable(this, R.drawable.ic_drawer);
    UiUtil.setColorIntToDrawable(config.getThemeColor(), drawable);
    toolbar.setNavigationIcon(drawable);

    if (config.isNightMode()) {
        setNightMode();
    } else {
        setDayMode();
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        int color;
        if (config.isNightMode()) {
            color = ContextCompat.getColor(this, R.color.black);
        } else {
            int[] attrs = { android.R.attr.navigationBarColor };
            TypedArray typedArray = getTheme().obtainStyledAttributes(attrs);
            color = typedArray.getColor(0, ContextCompat.getColor(this, R.color.white));
        }
        getWindow().setNavigationBarColor(color);
    }

    if (Build.VERSION.SDK_INT < 16) {
        // Fix for appBarLayout.fitSystemWindows() not being called on API < 16
        appBarLayout.setTopMargin(getStatusBarHeight());
    }
}

From source file:com.cenkgun.chatty.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    // Set default username is anonymous.
    mUsername = ANONYMOUS;//from w ww  .ja v  a 2s  .c  o m

    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirebaseUser = mFirebaseAuth.getCurrentUser();
    if (mFirebaseUser == null) {
        // Not signed in, launch the Sign In activity
        startActivity(new Intent(this, SignInActivity.class));
        finish();
        return;
    } else {
        mUsername = mFirebaseUser.getDisplayName();
        if (mFirebaseUser.getPhotoUrl() != null) {
            mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
        }
    }

    // Initialize Firebase Remote Config.
    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();

    // Define Firebase Remote Config Settings.
    FirebaseRemoteConfigSettings firebaseRemoteConfigSettings = new FirebaseRemoteConfigSettings.Builder()
            .setDeveloperModeEnabled(true).build();

    // Define default config values. Defaults are used when fetched config values are not
    // available. Eg: if an error occurred fetching values from the server.
    Map<String, Object> defaultConfigMap = new HashMap<>();
    defaultConfigMap.put("friendly_msg_length", 400L);

    // Apply config settings and default values.
    mFirebaseRemoteConfig.setConfigSettings(firebaseRemoteConfigSettings);
    mFirebaseRemoteConfig.setDefaults(defaultConfigMap);

    // Fetch remote config.
    fetchConfig();

    mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API).addApi(AppInvite.API).build();

    // Initialize ProgressBar and RecyclerView.
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(this);
    mLinearLayoutManager.setStackFromEnd(true);
    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);

    mProgressBar.setVisibility(ProgressBar.INVISIBLE);

    mMessageEditText = (EditText) findViewById(R.id.messageEditText);
    mMessageEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
            mSharedPreferences.getInt(CodelabPreferences.FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT)) });
    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    });

    mSendButton = (ImageButton) findViewById(R.id.sendButton);
    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ChattyMessage chattyMessage = new ChattyMessage(mMessageEditText.getText().toString(), mUsername,
                    mPhotoUrl, dateFormat.format(date), null /* no image */);
            mFirebaseDatabaseReference.child(MESSAGES_CHILD).push().setValue(chattyMessage);
            mMessageEditText.setText("");
        }
    });

    //        mAddMessageImageView = (ImageView) findViewById(R.id.addMessageImageView);
    //        mAddMessageImageView.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View view) {
    //                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    //                intent.addCategory(Intent.CATEGORY_OPENABLE);
    //                intent.setType("image/*");
    //                startActivityForResult(intent, REQUEST_IMAGE);
    //            }
    //        });

    // New child entries
    mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
    mFirebaseAdapter = new FirebaseRecyclerAdapter<ChattyMessage, MessageViewHolder>(ChattyMessage.class,
            R.layout.item_message, MessageViewHolder.class, mFirebaseDatabaseReference.child(MESSAGES_CHILD)) {

        @Override
        protected void populateViewHolder(final MessageViewHolder viewHolder, ChattyMessage chattyMessage,
                int position) {
            mProgressBar.setVisibility(ProgressBar.INVISIBLE);
            if (chattyMessage.getText() != null) {
                viewHolder.messageTextView.setText(chattyMessage.getText());
                viewHolder.messageTextView.setVisibility(TextView.VISIBLE);
                viewHolder.messageImageView.setVisibility(ImageView.GONE);
            } else {
                String imageUrl = chattyMessage.getImageUrl();
                if (imageUrl.startsWith("gs://")) {
                    StorageReference storageReference = FirebaseStorage.getInstance()
                            .getReferenceFromUrl(imageUrl);
                    storageReference.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                        @Override
                        public void onComplete(@NonNull Task<Uri> task) {
                            if (task.isSuccessful()) {
                                String downloadUrl = task.getResult().toString();
                                Glide.with(viewHolder.messageImageView.getContext()).load(downloadUrl)
                                        .into(viewHolder.messageImageView);
                            } else {
                                Log.w(TAG, "Getting download url was not successful.", task.getException());
                            }
                        }
                    });
                } else {
                    Glide.with(viewHolder.messageImageView.getContext()).load(chattyMessage.getImageUrl())
                            .into(viewHolder.messageImageView);
                }
                viewHolder.messageImageView.setVisibility(ImageView.VISIBLE);
                viewHolder.messageTextView.setVisibility(TextView.GONE);
            }

            viewHolder.messengerTime.setText(chattyMessage.getDate());
            viewHolder.messengerTextView.setText(chattyMessage.getName());

            if (chattyMessage.getPhotoUrl() == null) {
                viewHolder.messengerImageView.setImageDrawable(
                        ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_account_circle_black_36dp));
            } else {
                Glide.with(MainActivity.this).load(chattyMessage.getPhotoUrl())
                        .into(viewHolder.messengerImageView);
            }

        }
    };

    mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            int friendlyMessageCount = mFirebaseAdapter.getItemCount();
            int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
            // If the recycler view is initially being loaded or the
            // user is at the bottom of the list, scroll to the bottom
            // of the list to show the newly added message.
            if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1)
                    && lastVisiblePosition == (positionStart - 1))) {
                mMessageRecyclerView.scrollToPosition(positionStart);
            }
        }
    });

    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);

}

From source file:com.hippo.drawerlayout.DrawerLayout.java

public void setDrawerShadow(@DrawableRes int resId, int gravity) {
    setDrawerShadow(ContextCompat.getDrawable(getContext(), resId), gravity);
}

From source file:com.github.andrewlord1990.materialandroid.component.textfield.PasswordEditText.java

/**
 * Set the drawable to use for the visibility toggle when the password is currently being shown.
 *
 * @param shownDrawableRes Drawable to use for visibility toggle whilst password is being shown.
 *///from ww w  .  jav a  2s. co  m
public void setShownDrawable(@DrawableRes int shownDrawableRes) {
    shownIcon = ContextCompat.getDrawable(getContext(), shownDrawableRes);
    setPasswordVisibility();
}

From source file:com.facebook.react.views.textinput.ReactTextInputManager.java

private void setCursorColor(ReactEditText view, @Nullable Integer color) {
    // Evil method that uses reflection because there is no public API to changes
    // the cursor color programmatically.
    // Based on http://stackoverflow.com/questions/25996032/how-to-change-programatically-edittext-cursor-color-in-android.
    try {// w  ww .j a  v  a  2  s.c  o m
        // Get the original cursor drawable resource.
        Field cursorDrawableResField = TextView.class.getDeclaredField("mCursorDrawableRes");
        cursorDrawableResField.setAccessible(true);
        int drawableResId = cursorDrawableResField.getInt(view);

        Drawable drawable = ContextCompat.getDrawable(view.getContext(), drawableResId);
        if (color != null) {
            drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
        }
        Drawable[] drawables = { drawable, drawable };

        // Update the current cursor drawable with the new one.
        Field editorField = TextView.class.getDeclaredField("mEditor");
        editorField.setAccessible(true);
        Object editor = editorField.get(view);
        Field cursorDrawableField = editor.getClass().getDeclaredField("mCursorDrawable");
        cursorDrawableField.setAccessible(true);
        cursorDrawableField.set(editor, drawables);
    } catch (NoSuchFieldException ex) {
        // Ignore errors to avoid crashing if these private fields don't exist on modified
        // or future android versions.
    } catch (IllegalAccessException ex) {
    }
}

From source file:com.ez.gallery.ucrop.UCropActivity.java

/**
 * Configures and styles both status bar and toolbar.
 *///from   ww w.j  av  a 2s .  c  o m
private void setupAppBar() {
    setStatusBarColor(mStatusBarColor);

    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    // Set all of the Toolbar coloring
    toolbar.setBackgroundColor(mToolbarColor);
    toolbar.setTitleTextColor(mToolbarTextColor);
    toolbar.setSubtitleTextColor(mToolbarTextColor);

    ((TextView) toolbar.findViewById(R.id.toolbar_title)).setTextColor(mToolbarTextColor);

    // Color buttons inside the Toolbar
    Drawable stateButtonDrawable = ContextCompat.getDrawable(this, R.drawable.ucrop_ic_cross).mutate();
    stateButtonDrawable.setColorFilter(mToolbarTextColor, PorterDuff.Mode.SRC_ATOP);
    toolbar.setNavigationIcon(stateButtonDrawable);

    setSupportActionBar(toolbar);
    final ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayShowTitleEnabled(false);
    }
}

From source file:com.google.android.apps.santatracker.doodles.pursuit.PursuitFragment.java

private Drawable getShareImageDrawable(int starCount) {
    return ContextCompat.getDrawable(getActivity(), R.drawable.winner);
}