Search code examples
javaandroidandroid-actionbarandroid-toolbar

How to properly set an image and a text in the action bar?


I'm trying to set user's image and name in the action bar like so:

enter image description here

I'm not using a toolbar. The code:

if (receiverImageURL == null || receiverImageURL.trim().isEmpty()) {
    final Bitmap circleLetterTile = tileProvider.getCircularLetterTile(receiverFullName);
    getSupportActionBar().setIcon(new BitmapDrawable(getResources(), circleLetterTile));
    setTitle(" " +StringUtils.capitalizeFully(receiverFullName));
} else {
    Glide.with(this).asBitmap().load(receiverImageURL).into(new CustomViewTarget<ImageView, Bitmap>(???????) {

        @Override
        protected void onResourceCleared(@Nullable Drawable placeholder) {

        }

        @Override
        public void onLoadFailed(@Nullable Drawable errorDrawable) {
            final Bitmap circleLetterTile = tileProvider.getCircularLetterTile(receiverFullName);
            getSupportActionBar().setIcon(new BitmapDrawable(getResources(), circleLetterTile));
            setTitle(" " +StringUtils.capitalizeFully(receiverFullName));
        }

        @Override
        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
            final Bitmap circleAvatarBitmap = tileProvider.getCircularImage(resource);
            getSupportActionBar().setIcon(new BitmapDrawable(getResources(), circleAvatarBitmap));
            setTitle(" " +StringUtils.capitalizeFully(receiverFullName));
        }
    });
}

Which works if the user does not have an image (first if statement). But I have the following questions:

  1. When using Glide, I need to pass the ImageView id into the ????? place but I'm not sure how to get.
  2. I really don't like the space that I used in the setTitle(" " +StringUtils.capitalizeFully(receiverFullName)); for mocking the margin (took from other similar topic).

What would be easiest way to fix those two issues?


Solution

  • With an ActionBar you can use:

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setLogo(R.drawable.xxxx);
    

    enter image description here

    With a Toolbar:

        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setLogo(R.drawable.xxxxx);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    

    enter image description here