Search code examples
android-studioandroid-cardviewandroid-tvleanback

Placing an image/badge over the main image


I'm trying to place a mark or place a badge in my cardviews placing it in the middle of my card. The problem is, if I place the image with setMainimage both images show at the same time, the way I thought it would've worked was that first one shows, then followed by the second (which is smaller than the first), but that was not the case. The second way I tried was placing it with the styles but I'm using the same style for all my cards so the image is showing in all my cards. I would like some advice or some other way to do it.


Solution

  • There are a couple different ways you can achieve this. A simple way would be to just supply your own XML in the Presenter. In your XML, you can overlay your elements on top of each other however you'd like. Check this SO post for how to achieve it.

    @Override
    final protected BaseCardView onCreateView(Context context) {
        final BaseCardView cardView = new BaseCardView(context, null, R.style.YourCardStyle) {
            @Override
            public void setSelected(boolean selected) {
                // TODO: Add your functionality you want here! Showing/hiding elements.
                super.setSelected(selected);
            }
        };
    
        cardView.addView(LayoutInflater.from(context).inflate(R.layout.card_your_custom_view, null));
        // Just some init method to set up your views visibility.
        initCardView(cardView);
        return cardView;
    }
    

    Then as long as you name your views correctly in the XML, everything should work as you want. You'll bind the model to your views in onBindViewHolder

    public void onBindViewHolder(CardModel cardModel, BaseCardView cardView) {
        if (cardModel == null) {
            return;
        }
        Video video = cardModel.clip;
        Context context = cardView.getContext();
    
        ImageView imageView = (ImageView) cardView.findViewById(R.id.main_image);
        TextView primaryText = (TextView) cardView.findViewById(R.id.primary_text);
        TextView secondaryText = (TextView) cardView.findViewById(R.id.secondary_text);
        TextView extraText = (TextView) cardView.findViewById(R.id.extra_text);
    }
    

    With the above code blocks, you'll have to replace R.layout.card_your_custom_view with your layout file which has Views with IDs main_image, primary_text, secondary_text, and 'extra_text. As well as replacingR.style.YourCardStyle` with your own card style. Here are some examples of card styles you're allowed to use.

    To get a better understanding of Presenters, check out this folder in the Leanback Showcase app.

    Please let me know if this works.