'How to set the TMemo height to fill text content in Delphi firemonkey

I am using XE7.

I have a TMemo created in runtime.

I need enlarge your height to show all text lines.

I have tried these functions that I found on stackoverflow, but they aren´t working.

Memo.height:=get_memo_height(aMemo) and Memo.height:=ResizeMemo(aMemo)

I get height less than real height.

Regards, Luiz

//doesnt work
function get_memo_height(amemo:tmemo):single;
    var i:integer;
        astring:string;
        layout:ttextlayout;

    begin
      Layout := TTextLayoutManager.DefaultTextLayout.Create;
      astring:='';
      for i:=0 to amemo.lines.count-1 do astring:=astring+amemo.lines[i]+chr(10);
      Layout.BeginUpdate;
      Layout.Text :=astring;
      Layout.WordWrap := amemo.wordwrap;
      Layout.HorizontalAlign := amemo.TextAlign;
      Layout.MaxSize := PointF(amemo.width-amemo.ContentBounds.width,maxint);
      Layout.VerticalAlign := tTextAlign.taLeading;
      Layout.Font := amemo.Font;
      Layout.TopLeft := pointf(0,0);
      Layout.EndUpdate;
      result:=layout.textrect.bottom;
      Layout.free;
    end;



    //doesnt work
    function ResizeMemo(AMemo: TMemo):single;
    const
      Offset = 4; //The diference between ContentBounds and ContentLayout
    begin
      result := AMemo.ContentBounds.Height + Offset;
    end;


Solution 1:[1]

try this work arround:

put a TText component inside the TMemo, aligned to mostTop, set Autosize True, HistTest False, and Opacity to 0

then in a event perform this action:

procedure TfnuevoItem.Memo1KeyUp(Sender: TObject; var Key: Word;
  var KeyChar: Char; Shift: TShiftState);
begin
  Text1.Height:=0;
  Text1.Text:=Memo1.Text;
  Text1.RecalcSize;
  Memo1.Height:=Text1.Height+10; // set 10 or more offset
end;

Solution 2:[2]

Some extra manipulation on Neri Bocchi's code. The intention here was to mimic the behaviour of Telegram and WhatsApp on entering the text of a message. As opposed to Neri Bocchi, I use this code snippet on OnChangeTracking event because it updates the height of the TMemo when delete key is being pressed continuously.

TMainForm.Memo1OnChangeTracking(Sender: TObject);
begin
  Text1.Height := 40;
  Text1.Text := Memo1.Text;
  Text1.RecalcSize;
  if Text1.Height < 100 then
  begin
    if Text1.Height > 40 then
    begin
     Memo1.ShowScrollBars := false;
      lyMessage.Height := Text1.Height + 8; // set 10 or more offset
    end
    else
    begin
      Memo1.ShowScrollBars := false;
      lyMessage.Height := 48;
    end;
  end
  else
    Memo1.ShowScrollBars := true;
end;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Neri Bocchi
Solution 2 Costel Iordan