Centering a VectorDrawable in a RecyclerView ViewHolder

Nathan Sokalski 4,106 Reputation points
2024-10-06T22:00:08.9233333+00:00

I have a Xamarin.Android app that contains a RecyclerView, which uses a ViewHolder whose root element is a GridLayout. I have a VectorDrawable (a .xml file in my drawable folder) that I want to center in the ViewHolder. I have tried doing this several ways, and figured the best was to use an ImageView and call the SetImageDrawable method. However, the ImageView is not centered, and does not always seem to be the right size and does not seem to be centered. Here is my xml file:

<?xml version="1.0" encoding="utf-8"?>

<vector xmlns:android="http://schemas.android.com/apk/res/android"

android:width="2dp" android:height="52dp" android:viewportWidth="2" android:viewportHeight="52">

<path android:pathData="M1 25V-25" android:strokeColor="@color/Black" android:strokeLineCap="round" android:strokeWidth="2"/>

</vector>

As you can see, the VectorDrawable is just a simple vertical line (I also have a second xml file that is almost identical, just a shorter line). The only other View in my ViewHolder is a TextView. The only properties of the TextView that I make in my Adapter are Visibility & Text, so that works fine. For the ImageView, however, I set the Visibility, LayoutParameters.Height, and call SetImageDrawable. I set LayoutParameters.Height to match the height in the VectorDrawable. In the layout file used by the ViewHolder, the ImageView has layout_gravity set to center, which is where it appears in the Designer in Visual Studio 2022, but not when I debug it. I have tried adding RequestLayout(), Invalidate(), & ForceLayout() for the ImageView & root GridLayout, but it did not seem to make any difference. I don't care what I use to display the VectorDrawable, the important thing is that it is centered & that I can set it in code. Any suggestions?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,364 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,920 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.