Search code examples
xamarin.androidxamarin.formscustom-renderer

Xamarin.Forms CustomRenderer for a TextCell


I am trying to a create custom renderer for the first time. All I want to do is change fontsize of a TextCell in a ListView.

I have looked at the guide here http://developer.xamarin.com/guides/cross-platform/xamarin-forms/custom-renderer/ for an entry cell but have no idea what to do for a TextCell and can't find the info anywhere (it is probably very basic but I am very new to Xamarin)

The code for the Entry cell is as follows (for Android)

public class MyEntryRenderer : EntryRenderer
{
  // Override the OnElementChanged method so we can tweak this renderer post-initial setup
  protected override void OnElementChanged (ElementChangedEventArgs<Entry> e)
  {
    base.OnElementChanged (e));
    if (e.OldElement == null) {   // perform initial setup
      // lets get a reference to the native control
      var nativeEditText = (global::Android.Widget.EditText) Control;
      // do whatever you want to the textField here!
      nativeEditText.SetBackgroundColor(global::Android.Graphics.Color.DarkGray);
    }
  }
}

So in the case of a TextCell what am I overriding? (if i use OnElementChanged, it doesn't give me the OnElementChanged for base - it does give me OnCellPropertyChanged but if I use that for the method, then it seems to want PropertyChangedEventArgs then it doesn't like it --- I have no idea what to do, it is driving me nuts

Any suggestions appreciated


Solution

  • Not sure if this is what you're looking for, but this should work. You can manipulate both the Text view as well as the Detail view of the TextCell.

    I think you would be better off using a ViewCell though, since you can have more control over what is included and how it's rendered.

    class MyTextCellRenderer : TextCellRenderer
    {
        protected override View GetCellCore(Cell item, View convertView, ViewGroup parent, Context context)
        {
            var cell = (LinearLayout) base.GetCellCore(item, convertView, parent, context);
            var textView = (TextView)(cell.GetChildAt(1) as LinearLayout).GetChildAt(0);
            var detailView = (TextView)(cell.GetChildAt(1) as LinearLayout).GetChildAt(1);
            textView.TextSize = textView.DipsToPixels(32);
            return cell;
        }
    }
    
    public static class LayoutHelperExtensions
    {
        public static int DipsToPixels(this View view, float dip)
        {
            return (int) Math.Round(TypedValue.ApplyDimension(ComplexUnitType.Dip, dip, view.Resources.DisplayMetrics));
        }
    }