The RecyclerView will be using a GridLayoutManager, and the number of items is known, so I want to make it fit without the need for scrolling.
If you want to achieve the above function, try using the following code. It doesn't need to caculate each row's height of the gridLayout.
public class TestAdapter : RecyclerView.Adapter
{
public ObservableCollection<TestModel> list;
TestViewHolder viewHolder;
RecyclerView _recyclerView;
public TestAdapter(ObservableCollection<TestModel> list, IOnStartDragListener dragStartListener)
{
this.list = list;
this.dragStartListener = dragStartListener;
}
...
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(MainActivity.Instance).Inflate(Resource.Layout.recyclerView_itemLayout, parent, false);
TestViewHolder viewHolder = new TestViewHolder(itemView);
var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
var height = mainDisplayInfo.Height;
var recyclerViewheight = _recyclerView.Height;
var manager = _recyclerView.GetLayoutManager() as GridLayoutManager;
int spanCount = manager.SpanCount;
var rows = (int)Math.Ceiling(list.Count / Convert.ToDecimal(spanCount));
int deviceheight = recyclerViewheight / rows;
viewHolder.ItemView.LayoutParameters.Height = deviceheight;
return viewHolder;
}
public override void OnAttachedToRecyclerView(RecyclerView recyclerView)
{
base.OnAttachedToRecyclerView(recyclerView);
this._recyclerView = recyclerView;
}
}
You only needs to specify the spanCount of the GridLayoutManager in the Activity class, the recyclerView will be placed to fit the screen automatically.
public class MainActivity : AppCompatActivity
{
public static MainActivity Instance;
public static RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
TestAdapter testAdapter;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.activity_main);
Instance = this;
recyclerView = FindViewById<RecyclerView>(Resource.Id.test_recyclerView);
layoutManager = new GridLayoutManager(this, 4);
data = new ObservableCollection<TestModel>();
//add items to the collection
testAdapter = new TestAdapter(data, this);
recyclerView.SetLayoutManager(layoutManager);
recyclerView.SetAdapter(testAdapter);
}
}