Android Code Snippet [B4X] Auto Height Webview

For B4i:
Run this JavaScript code after the page is loaded:
Sub webview_PageFinished (Success As Boolean, Url As String)
    wait for (webview.EvaluateJavaScript("document.documentElement.scrollHeight")) webview_JSComplete (Success As Boolean, Result As String)
    If Success Then webview.Height = DipToCurrent(Result)
End Sub
If you are using LoadHtml then add this following code before your html text
HTML:
<head><meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'/></head>

For B4A:
Dependency:
WebViewExtras2 (v2.20)

Add WebViewExtra and DefaultJavascriptInterface variable in Global Sub:
Sub Globals
    Dim wve As WebViewExtras
    Dim jsi As DefaultJavascriptInterface
End Sub

Initialize WebViewExtra and DefaultJavascriptInterface before loading content in WebView:
wve.Initialize(webview)
jsi.Initialize
wve.AddJavascriptInterface(jsi,"B4A")

Run this JavaScript code after the page is loaded:
Sub webview_PageFinished (Url As String)
    wve.ExecuteJavascript("B4A.CallSub('SetWVHeight',true, document.documentElement.scrollHeight);")
End Sub

Sub SetWVHeight(height As String)
    webview.Height = DipToCurrent(height)
End Sub
 
Last edited:

JohnC

Expert
Licensed User
Longtime User
I don't exactly understand what this code does?
 

Biswajit

Active Member
Licensed User
Longtime User
I don't exactly understand what this code does?
The javascript code "document.documentElement.scrollHeight" return the actual height of the webview content in DIP unit. Then the B4A sub convert the unit and set the webview height to fit the inner content.

So anyone wants to show a rich text with css style can show in a webview which will not show any scrollbar as the webview height will be changed to fit the inner content.
 
Last edited:

JohnC

Expert
Licensed User
Longtime User
So this code is to allow a webview to change it's height depending on the inner content of the page?
 

Biswajit

Active Member
Licensed User
Longtime User

luke2012

Well-Known Member
Licensed User
Longtime User
The javascript code "document.documentElement.scrollHeight" return the actual height of the webview content in DIP unit. Then the B4A sub convert the unit and set the webview height to fit the inner content.

So anyone wants to show a rich text with css style can show in a webview which will not show any scrollbar as the webview height will be changed to fit the inner content.

Great solution :) I'll try it today!
Where I can find WebViewExtras2 ? Searching within B4A Library tab I can't find it.
 
Last edited:

fredo

Well-Known Member
Licensed User
Longtime User
Where I can find WebViewExtras2 ?

Normally the lib was available here: http://b4a.martinpearman.co.uk/webviewextras/
But the link is not available right now.

I'm leaning far out of the window and attach @warwound 's lib here.
2020-08-27_09-43-30.png

@warwound, please let me know if this is not okay...
 

Attachments

  • wwx2.zip
    41.4 KB · Views: 724
Last edited:

luke2012

Well-Known Member
Licensed User
Longtime User
For B4i:
Run this JavaScript code after the page is loaded:
Sub webview_PageFinished (Success As Boolean, Url As String)
    wait for (webview.EvaluateJavaScript("document.documentElement.scrollHeight")) webview_JSComplete (Success As Boolean, Result As String)
    If Success Then webview.Height = DipToCurrent(Result)
End Sub
If you are using LoadHtml then add this following code before your html text
HTML:
<head><meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'/></head>

For B4A:
Dependency:
WebViewExtras2 (v2.20)

Add WebViewExtra and DefaultJavascriptInterface variable in Global Sub:
Sub Globals
    Dim wve As WebViewExtras
    Dim jsi As DefaultJavascriptInterface
End Sub

Initialize WebViewExtra and DefaultJavascriptInterface before loading content in WebView:
wve.Initialize(webview)
jsi.Initialize
wve.AddJavascriptInterface(jsi,"B4A")

Run this JavaScript code after the page is loaded:
Sub webview_PageFinished (Url As String)
    wve.ExecuteJavascript("B4A.CallSub('SetWVHeight',true, document.documentElement.scrollHeight);")
End Sub

Sub SetWVHeight(height As String)
    webview.Height = DipToCurrent(height)
End Sub

Hi @Biswajit.
I'm testing the Android version implementation but the webview doesn't resize :-(
I'm trying to understand where is the problem:

I'm implementing this within a B4XPages App:

1) I'm using the wwx2.zip library (attached to this post): WebViewExtras2 (v2.20)
2)I declared within the WebViewExtras and DefaultJavascriptInterface within Class_Globals
B4X:
Sub Class_Globals
    Private Root As B4XView 'ignore
    Private xui As XUI 'ignore
      
    'WebView autoresize
    Dim wve As WebViewExtras
    Dim jsi As DefaultJavascriptInterface
End Sub

3) I Initialized WebViewExtra and DefaultJavascriptInterface before loading content in WebView
B4X:
    'WebView autoresize
    #if B4A
        wve.Initialize(lblCardDesc)
        jsi.Initialize
        wve.AddJavascriptInterface(jsi,"B4A")
        lblCardDesc.LoadHtml(cfv.Desc)
    #End If
    #if B4i
        private htmlHead as string = $"<head><meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'/></head>
        private htmlDesc as string = cfv.Desc
        lblCardDesc.LoadHtml(htmlHead & htmlDesc)
    #End If

3) I runned the JavaScript code after the page is loaded
B4X:
    #if B4A
        Sub lblCardDesc_PageFinished (Url As String)
            wve.ExecuteJavascript("B4A.CallSub('SetWVHeight',true, document.documentElement.scrollHeight);")
        End Sub

        Sub SetWVHeight(height As String)
            lblCardDesc.Height = DipToCurrent(height)
        End Sub
    #End If
    
    #if B4i
        Sub lblCardDesc_PageFinished (Success As Boolean, Url As String)
               wait for (lblCardDesc.EvaluateJavaScript("document.documentElement.scrollHeight")) lblCardDesc_JSComplete (Success As Boolean, Result As String)
            If Success Then lblCardDesc.Height = DipToCurrent(Result)
        End Sub
    #End If

4) Within the B4A Designer (WebView Properties) I have "JavaScriptEnabled" flagged (on) and ZoomEnabled de-flagged (off).

But ... when I run it it doesn't resize (see attached images).
Screen1: There is only 1 line of text
screen1.png


Screen2: Many lines but the last 4 lines isn't displayedWhere I'm wrong ?
screen2.png
Thanks in advance for your preciuos help :)
Luca.
 

Biswajit

Active Member
Licensed User
Longtime User
Do not attach image in full size it makes the post unreadable.

It seems like your text content height is more than the free space available in your app. so you have to add the webview inside a scrollview.
Or
Change this following code
B4X:
Dim maxheight = 100%y - (topbar.height + bottombar.height)
lblCardDesc.Height =  Min(maxheight, DipToCurrent(height))
 

luke2012

Well-Known Member
Licensed User
Longtime User
Do not attach image in full size it makes the post unreadable.

It seems like your text content height is more than the free space available in your app. so you have to add the webview inside a scrollview.
Or
Change this following code
B4X:
Dim maxheight = 100%y - (topbar.height + bottombar.height)
lblCardDesc.Height =  Min(maxheight, DipToCurrent(height))

Thanks for your quick reply!
1) "so you have to add the webview inside a scrollview" ---> The webview is inside a CustomListView (within the ListView inner panel).
B4X:
    Private clvCardFull As CustomListView
    Private pnl As B4XView = CreateItem (ItemVal)
    clvCardFull.Add(pnl, ItemVal)

2) I'll try the code.

As alternative way, is it possibile to set the webview as fixed height and let the user to scroll the text inside ?
 
Last edited:

Biswajit

Active Member
Licensed User
Longtime User
Thanks for your quick reply!
1) "so you have to add the webview inside a scrollview" ---> The webview is inside a CustomListView (within the ListView inner panel).
B4X:
    Private clvCardFull As CustomListView
    Private pnl As B4XView = CreateItem (ItemVal)
    clvCardFull.Add(pnl, ItemVal)

2) I'll try the code.

As alternative way, is it possibile to set the webview as fixed height and let the user to scroll the text inside ?
If its inside a CLV then you have to call ResizeItem to resize the panel containing the Webview

As alternative way, is it possibile to set the webview as fixed height and let the user to scroll the text inside ?
That is what this code does
Change this following code
B4X:
Dim maxheight = 100%y - (topbar.height + bottombar.height)
lblCardDesc.Height =  Min(maxheight, DipToCurrent(height))
 

Lucas Siqueira

Active Member
Licensed User
Longtime User
I created a code in b4xpages that makes the adjustment; for anyone who needs it, here's an example.:

B4XMainPage
B4X:
#Region Shared Files
#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files"
'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True
#End Region

'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=%PROJECT_NAME%.zip

Sub Class_Globals
    ' Root container of the page
    Private Root As B4XView
    Private xui As XUI
 
    '---------------------- WebView resize helper ----------------------
    ' Auxiliary WebView used only to calculate the correct height
    Private redimencionarWebView As WebView
 
    #If b4a
    ' Used to execute JavaScript on Android WebView
    Dim wve As WebViewExtras
    Dim jsi As DefaultJavascriptInterface
    #End If
    '-------------------------------------------------------------------
 
    ' List of HTML texts to display
    Private Texts As List
 
    ' Main WebViews displayed on screen
    Private WebView1 As WebView
    Private WebView2 As WebView
End Sub

Public Sub Initialize
End Sub

Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
 
    ' Load layout
    Root.LoadLayout("MainPage")
 
    #if b4i
    ' Wait for resize event on iOS before continuing
    Wait For B4XPage_Resize (Width As Int, Height As Int)
    #End If
 
    '---------------------- WebView resize setup ----------------------
    ' Initialize hidden WebView used for measuring content height
    redimencionarWebView.Initialize("redimencionarWebView")
    Root.AddView(redimencionarWebView, 0, Root.Height, Root.Width, 10dip)
    redimencionarWebView.Visible = True
 
    #If b4a
    ' Initialize JavaScript interface for Android
    wve.Initialize(redimencionarWebView)
    jsi.Initialize
    wve.AddJavascriptInterface(jsi, "B4A")
    #End If
    '-------------------------------------------------------------------
 
    ' Initialize list of sample texts
    Texts.Initialize

    ' Add multiple HTML samples (student behavior reports)
    Texts.Add("<p>Hello</p><p>Lucas participated well in today's activity and interacted with his classmates.</p>")
    Texts.Add("<p>Hello</p><p>Maria had difficulty concentrating today, getting up several times during class.</p>")
    Texts.Add("<p>Hello</p><p>Pedro showed calm behavior, completed the proposed activities, and helped his classmates.</p>")
    Texts.Add("<p>Hello</p><p>Julia was very agitated today, ran around the classroom, pushed classmates, and had difficulty following instructions. She required several interventions from the teacher.</p>")
    Texts.Add("<p>Hello</p><p>Gabriel had a productive day. He participated in activities, responded well to instructions, and showed interest.</p>")
    Texts.Add("<p>Hello</p><p>Ana showed challenging behavior today. She refused to participate in activities, shouted at times, and needed to be removed from the classroom to calm down. After some time, she returned calmer.</p>")
    Texts.Add("<p>Hello</p><p>Rafael showed significant progress today. He was able to stay focused longer and interacted positively with classmates during group activities.</p>")
    Texts.Add("<p>Hello</p><p>Beatriz was restless for most of the period. She ran around the classroom, tried to climb on furniture, and had difficulty respecting limits. She was redirected several times.</p>")
    Texts.Add("<p>Hello</p><p>Matheus had excellent behavior today. He participated in all activities, respected his classmates, and followed instructions independently.</p>")
    Texts.Add("<p>Hello</p><p>Carla showed mixed behavior today. At times she participated well, but at others she became agitated, pushed classmates, and had difficulty controlling her emotions. We reinforced the importance of discussing this at home.</p>")
    Texts.Add("<p>Hello</p><p>Bruno was attentive during most of the class and completed his tasks with minimal assistance.</p>")
    Texts.Add("<p>Hello</p><p>Fernanda showed improvement in following instructions and staying seated during activities.</p>")
    Texts.Add("<p>Hello</p><p>Diego had some difficulty sharing materials with classmates but responded well after guidance.</p>")
    Texts.Add("<p>Hello</p><p>Larissa participated in group activities and demonstrated good teamwork skills.</p>")
    Texts.Add("<p>Hello</p><p>Eduardo was distracted at times but managed to complete his activities with encouragement.</p>")
    Texts.Add("<p>Hello</p><p>Camila was calm and cooperative, following classroom rules appropriately.</p>")
    Texts.Add("<p>Hello</p><p>Matheus had excellent behavior today. He participated in all activities with great enthusiasm, respected his classmates, and followed instructions independently. He also demonstrated responsibility by organizing his materials and helping maintain a positive classroom environment. His interaction with peers was respectful and cooperative throughout the day.</p>")
    Texts.Add("<p>Hello</p><p>Julia showed a positive attitude during today's activities. Although she needed a few reminders to stay focused, she was able to complete her tasks successfully. She interacted well with her classmates and showed kindness during group work. We encourage her to continue improving her concentration and maintaining this positive behavior.</p>")
    Texts.Add("<p>Hello</p><p>Gabriel had a productive day overall. He actively participated in class discussions and showed interest in the proposed activities. At times, he became slightly distracted, but responded well to guidance. He demonstrated good problem-solving skills and worked well both independently and in groups.</p>")
    Texts.Add("<p>Hello</p><p>Maria had some challenges today with maintaining focus during longer activities. She needed frequent redirection and support from the teacher. However, she showed improvement as the day progressed and was able to complete part of her work. It is important to continue reinforcing routines and encouraging her engagement.</p>")
    Texts.Add("<p>Hello</p><p>Lucas demonstrated great progress today. He remained focused for longer periods, followed instructions carefully, and completed all assigned activities. He also interacted positively with classmates and showed respect for classroom rules. We are very pleased with his development.</p>")
    Texts.Add("<p>Hello</p><p>Beatriz showed moments of restlessness during the class. She had difficulty staying seated and following some instructions, requiring several reminders. Despite this, she was able to participate in certain activities and showed willingness to improve. Continued support and reinforcement at home would be beneficial.</p>")
    Texts.Add("<p>Hello</p><p>Rafael had an excellent day. He demonstrated autonomy in completing his tasks, helped classmates when needed, and followed all instructions without difficulty. His behavior was exemplary, and he contributed positively to the classroom environment.</p>")
    Texts.Add("<p>Hello</p><p>Ana presented mixed behavior today. During some periods, she was focused and participated actively. However, at other times she became distracted and had difficulty managing her emotions. With support, she was able to regain control and continue her activities. We recommend reinforcing emotional regulation strategies.</p>")
 
    ' Trigger initial load
    Panel1_Click
End Sub

Sub B4XPage_Appear
End Sub

Private Sub Panel1_Click
    Dim html As String = ""
 
    ' Select random text
    html = Texts.Get(Rnd(0, Texts.Size))
 
    #if b4i
    ' Add viewport meta for proper scaling on iOS
    html = "<head><meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'/></head>" & html
    #End If
 
    ' Load and resize first WebView
    loadHtmlAndResize(WebView1, html)
    Wait For loadHtmlAndResizeComplete(Height1 As Int)
 
    '-------------------------
 
    ' Position second WebView below the first
    WebView2.Top = ((WebView1.Top + WebView1.Height) + 20dip)
 
    ' Select another random text
    html = Texts.Get(Rnd(0, Texts.Size))
 
    #if b4i
    html = "<head><meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'/></head>" & html
    #End If
 
    ' Load and resize second WebView
    loadHtmlAndResize(WebView2, html)
    Wait For loadHtmlAndResizeComplete(Height1 As Int)
 
End Sub

'---------------------- WebView resize logic ----------------------
Sub loadHtmlAndResize(xWebView1 As WebView, xHtml1 As String)
    Dim finalHeight As Int = 0
 
    ' Match helper WebView width to target WebView
    redimencionarWebView.Width = xWebView1.Width
 
    ' Clear previous content
    redimencionarWebView.LoadHtml("")
    xWebView1.LoadHtml("")
 
    ' Reset heights
    redimencionarWebView.Height = 0
    xWebView1.Height = 0
 
    ' Load HTML into both WebViews
    redimencionarWebView.LoadHtml(xHtml1)
    xWebView1.LoadHtml(xHtml1)

    #if b4a
    ' Wait for page load
        Wait For redimencionarWebView_PageFinished(Url As String)
        Sleep(150)

    ' Execute JavaScript to get content width and height
        wve.ExecuteJavascript("B4A.CallSub('SetWVHeight', true, " & _
        "document.documentElement.scrollWidth + ',' + document.documentElement.scrollHeight);")
     
    ' Receive result from JavaScript
        Wait For SetWVHeight(Result As String)
        Log("result: " & Result)

        Dim parts() As String = Regex.Split(",", Result)
        Dim cssWidth As Float = parts(0)
        Dim cssHeight As Float = parts(1)

    ' Calculate scale factor
        Dim b4xWidth As Float = redimencionarWebView.Width
        Dim scale As Float = cssWidth / b4xWidth

    ' Debug logs
        Log("cssWidth: " & cssWidth)
        Log("cssHeight: " & cssHeight)
        Log("b4xWidth (DIPs): " & b4xWidth)
        Log("scale: " & scale)
        Log("finalHeight (DIPs): " & (cssHeight / scale))

    ' Apply calculated height
        finalHeight = cssHeight / scale
        redimencionarWebView.Height = finalHeight
        xWebView1.Height = finalHeight
     
    #Else b4i
 
    ' Wait for page load on iOS
    Wait For redimencionarWebView_PageFinished (Success As Boolean, Url As String)
     
    ' Execute JavaScript to get content height
    wait for (redimencionarWebView.EvaluateJavaScript("document.documentElement.scrollHeight")) redimencionarWebView_JSComplete (Success As Boolean, Result As String)
     
    If Success Then
        finalHeight = DipToCurrent(Result)
        redimencionarWebView.Height = finalHeight
        xWebView1.Height = finalHeight
    End If
     
    #End If
 
    ' Notify completion with calculated height
    CallSubDelayed2(Me,"loadHtmlAndResizeComplete", finalHeight)
End Sub
'-------------------------------------------------------------------

1773935933239.png
 

Attachments

  • teste_webview_altura.zip
    19.7 KB · Views: 5
Last edited:

Lucas Siqueira

Active Member
Licensed User
Longtime User
I added a project with two pages and now I'm using height adjustment as a function.


B4XMainPage
B4X:
#Region Shared Files
#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files"
'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True
#End Region

'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=%PROJECT_NAME%.zip

Sub Class_Globals
    ' Root container of the page
    Private Root As B4XView
    Private xui As XUI
    
    Public pgPage2 As pPage2
    
    '---------------------- WebView resize helper ----------------------
    ' Auxiliary WebView used only to calculate the correct height
    Private resizeWebView As WebView
    
    #If b4a
    ' Used to execute JavaScript on Android WebView
    Dim wve As WebViewExtras
    Dim jsi As DefaultJavascriptInterface
    #End If
    '-------------------------------------------------------------------
    
End Sub

Public Sub Initialize
End Sub

Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    
    B4XPages.AddPage("pgPage2", pgPage2.Initialize)
    
    #if b4i
    ' Wait for resize event on iOS before continuing
    Wait For B4XPage_Resize (Width As Int, Height As Int)
    #End If
    
    '---------------------- WebView resize setup ----------------------
    ' Initialize hidden WebView used for measuring content height
    resizeWebView.Initialize("resizeWebView")
    Root.AddView(resizeWebView, 0, Root.Height, Root.Width, 10dip)
        
    #If b4a
    ' Initialize JavaScript interface for Android
    wve.Initialize(resizeWebView)
    jsi.Initialize
    wve.AddJavascriptInterface(jsi, "B4A")
    #End If
    '-------------------------------------------------------------------
    
    
End Sub

Sub B4XPage_Appear
    B4XPages.ShowPage("pgPage2")
End Sub




#Region LOADHTML

'---------------------- WebView resize logic ----------------------
Public Sub loadHtmlAndResize2(xCallback1 As Object, xWebView1 As WebView, xHtml1 As String)
    #if b4i
    ' Add viewport meta for proper scaling on iOS
    xHtml1 = "<head><meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'/></head>" & xHtml1
    #End If
    
    loadHtmlAndResize(xCallback1, xWebView1, xHtml1)
End Sub

Public Sub loadHtmlAndResize(xCallback1 As Object, xWebView1 As WebView, xHtml1 As String)
    Dim finalHeight As Int = 0
    
    ' Match helper WebView width to target WebView
    resizeWebView.Width = xWebView1.Width
    
    ' Clear previous content
    resizeWebView.LoadHtml("")
    xWebView1.LoadHtml("")
    
    ' Reset heights
    resizeWebView.Height = 0
    xWebView1.Height = 0
    
    ' Load HTML into both WebViews
    resizeWebView.LoadHtml(xHtml1)
    xWebView1.LoadHtml(xHtml1)

    #if b4a
    ' Wait for page load
        Wait For resizeWebView_PageFinished(Url As String)
        Sleep(150)

    ' Execute JavaScript to get content width and height
        wve.ExecuteJavascript("B4A.CallSub('SetWVHeight', true, " & _
        "document.documentElement.scrollWidth + ',' + document.documentElement.scrollHeight);")
        
    ' Receive result from JavaScript
        Wait For SetWVHeight(Result As String)
        Log("result: " & Result)

        Dim parts() As String = Regex.Split(",", Result)
        Dim cssWidth As Float = parts(0)
        Dim cssHeight As Float = parts(1)

    ' Calculate scale factor
        Dim b4xWidth As Float = resizeWebView.Width
        Dim scale As Float = cssWidth / b4xWidth

    ' Debug logs
        Log("cssWidth: " & cssWidth)
        Log("cssHeight: " & cssHeight)
        Log("b4xWidth (DIPs): " & b4xWidth)
        Log("scale: " & scale)
        Log("finalHeight (DIPs): " & (cssHeight / scale))

    ' Apply calculated height
        finalHeight = cssHeight / scale
        resizeWebView.Height = finalHeight
        xWebView1.Height = finalHeight
        
    #Else b4i
    
    ' Wait for page load on iOS
    Wait For resizeWebView_PageFinished (Success As Boolean, Url As String)
        
    ' Execute JavaScript to get content height
    wait for (resizeWebView.EvaluateJavaScript("document.documentElement.scrollHeight")) resizeWebView_JSComplete (Success As Boolean, Result As String)
        
    If Success Then
        finalHeight = DipToCurrent(Result)
        resizeWebView.Height = finalHeight
        xWebView1.Height = finalHeight
    End If
        
    #End If
    
    ' Notify completion with calculated height
    CallSubDelayed2(xCallback1,"loadHtmlAndResizeComplete", finalHeight)
End Sub
'-------------------------------------------------------------------

#End Region


pPage2
B4X:
Sub Class_Globals
    Private Root As B4XView 'ignore
    Private xui As XUI 'ignore

    ' List of HTML texts to display
    Private Texts As List
    
    ' Main WebViews displayed on screen
    Private WebView1 As WebView
    Private WebView2 As WebView
End Sub

Public Sub Initialize As Object
    Return Me
End Sub

Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
        
    ' Load layout
    Root.LoadLayout("MainPage")
    
    #if b4i
    ' Wait for resize event on iOS before continuing
    Wait For B4XPage_Resize (Width As Int, Height As Int)
    #End If
    
    ' Initialize list of sample texts
    Texts.Initialize

    ' Add multiple HTML samples (student behavior reports)
    Texts.Add("<p>Hello</p><p>Lucas participated well in today's activity and interacted with his classmates.</p>")
    Texts.Add("<p>Hello</p><p>Maria had difficulty concentrating today, getting up several times during class.</p>")
    Texts.Add("<p>Hello</p><p>Pedro showed calm behavior, completed the proposed activities, and helped his classmates.</p>")
    Texts.Add("<p>Hello</p><p>Julia was very agitated today, ran around the classroom, pushed classmates, and had difficulty following instructions. She required several interventions from the teacher.</p>")
    Texts.Add("<p>Hello</p><p>Gabriel had a productive day. He participated in activities, responded well to instructions, and showed interest.</p>")
    Texts.Add("<p>Hello</p><p>Ana showed challenging behavior today. She refused to participate in activities, shouted at times, and needed to be removed from the classroom to calm down. After some time, she returned calmer.</p>")
    Texts.Add("<p>Hello</p><p>Rafael showed significant progress today. He was able to stay focused longer and interacted positively with classmates during group activities.</p>")
    Texts.Add("<p>Hello</p><p>Beatriz was restless for most of the period. She ran around the classroom, tried to climb on furniture, and had difficulty respecting limits. She was redirected several times.</p>")
    Texts.Add("<p>Hello</p><p>Matheus had excellent behavior today. He participated in all activities, respected his classmates, and followed instructions independently.</p>")
    Texts.Add("<p>Hello</p><p>Carla showed mixed behavior today. At times she participated well, but at others she became agitated, pushed classmates, and had difficulty controlling her emotions. We reinforced the importance of discussing this at home.</p>")
    Texts.Add("<p>Hello</p><p>Bruno was attentive during most of the class and completed his tasks with minimal assistance.</p>")
    Texts.Add("<p>Hello</p><p>Fernanda showed improvement in following instructions and staying seated during activities.</p>")
    Texts.Add("<p>Hello</p><p>Diego had some difficulty sharing materials with classmates but responded well after guidance.</p>")
    Texts.Add("<p>Hello</p><p>Larissa participated in group activities and demonstrated good teamwork skills.</p>")
    Texts.Add("<p>Hello</p><p>Eduardo was distracted at times but managed to complete his activities with encouragement.</p>")
    Texts.Add("<p>Hello</p><p>Camila was calm and cooperative, following classroom rules appropriately.</p>")
    Texts.Add("<p>Hello</p><p>Matheus had excellent behavior today. He participated in all activities with great enthusiasm, respected his classmates, and followed instructions independently. He also demonstrated responsibility by organizing his materials and helping maintain a positive classroom environment. His interaction with peers was respectful and cooperative throughout the day.</p>")
    Texts.Add("<p>Hello</p><p>Julia showed a positive attitude during today's activities. Although she needed a few reminders to stay focused, she was able to complete her tasks successfully. She interacted well with her classmates and showed kindness during group work. We encourage her to continue improving her concentration and maintaining this positive behavior.</p>")
    Texts.Add("<p>Hello</p><p>Gabriel had a productive day overall. He actively participated in class discussions and showed interest in the proposed activities. At times, he became slightly distracted, but responded well to guidance. He demonstrated good problem-solving skills and worked well both independently and in groups.</p>")
    Texts.Add("<p>Hello</p><p>Maria had some challenges today with maintaining focus during longer activities. She needed frequent redirection and support from the teacher. However, she showed improvement as the day progressed and was able to complete part of her work. It is important to continue reinforcing routines and encouraging her engagement.</p>")
    Texts.Add("<p>Hello</p><p>Lucas demonstrated great progress today. He remained focused for longer periods, followed instructions carefully, and completed all assigned activities. He also interacted positively with classmates and showed respect for classroom rules. We are very pleased with his development.</p>")
    Texts.Add("<p>Hello</p><p>Beatriz showed moments of restlessness during the class. She had difficulty staying seated and following some instructions, requiring several reminders. Despite this, she was able to participate in certain activities and showed willingness to improve. Continued support and reinforcement at home would be beneficial.</p>")
    Texts.Add("<p>Hello</p><p>Rafael had an excellent day. He demonstrated autonomy in completing his tasks, helped classmates when needed, and followed all instructions without difficulty. His behavior was exemplary, and he contributed positively to the classroom environment.</p>")
    Texts.Add("<p>Hello</p><p>Ana presented mixed behavior today. During some periods, she was focused and participated actively. However, at other times she became distracted and had difficulty managing her emotions. With support, she was able to regain control and continue her activities. We recommend reinforcing emotional regulation strategies.</p>")
    
    ' Trigger initial load
    Panel1_Click
End Sub

Sub B4XPage_Appear
End Sub

Private Sub Panel1_Click
    
    Dim html As String = ""
    
    ' Select random text
    html = Texts.Get(Rnd(0, Texts.Size))
    
    ' Load and resize first WebView
    B4XPages.MainPage.loadHtmlAndResize2(Me, WebView1, html)
    Wait For loadHtmlAndResizeComplete(Height1 As Int)
    
    '-------------------------
    
    ' Position second WebView below the first
    WebView2.Top = ((WebView1.Top + WebView1.Height) + 20dip)
    
    ' Select another random text
    html = Texts.Get(Rnd(0, Texts.Size))
    
    ' Load and resize second WebView
    B4XPages.MainPage.loadHtmlAndResize2(Me, WebView2, html)
    Wait For loadHtmlAndResizeComplete(Height1 As Int)
    
End Sub

1773949892800.png
 

Attachments

  • teste_webview_altura_2_pages.zip
    18.4 KB · Views: 6

Lucas Siqueira

Active Member
Licensed User
Longtime User
The project is working and has been tested in B4A and B4I.

I discovered there was an error when trying to use resizing within a custom list view (clv). I've now made the final adjustments, and the attached code includes both examples without and with clv.

I made the background of the item card light red to better identify if the webview was resized to the correct size.

B4XMainPage
B4XMainPage:
#Region Shared Files
#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files"
'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True
#End Region

'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=%PROJECT_NAME%.zip

Sub Class_Globals
    ' Root container of the page
    Private Root As B4XView
    Private xui As XUI
 
    Public pgPage2 As pPage2
    Public pgPage3 As pPage3
End Sub

Public Sub Initialize
End Sub

Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
 
    B4XPages.AddPage("pgPage2", pgPage2.Initialize)
    B4XPages.AddPage("pgPage3", pgPage3.Initialize)
 
    ' Load layout
    Root.LoadLayout("MainPage")
 
    #if b4i
    ' Wait for resize event on iOS before continuing
    Wait For B4XPage_Resize (Width As Int, Height As Int)
    #End If
End Sub

Sub B4XPage_Appear
End Sub

Private Sub pnlPage2_Click
    B4XPages.ShowPage("pgPage2")
End Sub

Private Sub pnlPage3_Click
    B4XPages.ShowPage("pgPage3")
End Sub

#Region LOADHTML

'---------------------- WebView resize logic ----------------------
Public Sub loadHtmlAndResize2(xCallback1 As Object, xParent1 As B4XView, xWebView1 As WebView, xHtml1 As String)
    #if b4i
    ' Add viewport meta for proper scaling on iOS
    xHtml1 = "<head><meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'/></head>" & xHtml1
    #End If
 
    loadHtmlAndResize(xCallback1, xParent1, xWebView1, xHtml1)
End Sub

Public Sub loadHtmlAndResize(xCallback1 As Object, xParent1 As B4XView, xWebView1 As WebView, xHtml1 As String)
    Dim finalHeight As Int = 0
 
    Dim newWebView As WebView
    newWebView.Initialize("newWebView")
 
    #if b4a
    newWebView.SetLayoutAnimated(0, 0, 0, xWebView1.Width, 100dip)
    #else if b4i
    newWebView.SetLayoutAnimated(0, 0, 0, 0, xWebView1.Width, 100dip)
    #End If
 
    xParent1.AddView(newWebView, 0, 0, newWebView.Width, newWebView.Height)
 
    #If b4a
    ' Used to execute JavaScript on Android WebView
    Dim wve2 As WebViewExtras
    Dim jsi2 As DefaultJavascriptInterface
    #End If
 
    #If b4a
    ' Initialize JavaScript interface for Android
    wve2.Initialize(newWebView)
    jsi2.Initialize
    wve2.AddJavascriptInterface(jsi2, "B4A")
    #End If
 
    ' Reset heights
    newWebView.Height = 0
    xWebView1.Height = 0
 
    ' Load HTML into both WebViews
    newWebView.LoadHtml(xHtml1)
    xWebView1.LoadHtml(xHtml1)

    #if b4a
    ' Wait for page load
    Wait For newWebView_PageFinished(Url As String)

    ' Execute JavaScript to get content width and height
    wve2.ExecuteJavascript("B4A.CallSub('SetWVHeight', true, " & _
        "document.documentElement.scrollWidth + ',' + document.documentElement.scrollHeight);")
     
    ' Receive result from JavaScript
    Wait For SetWVHeight(Result As String)
    Log("result: " & Result)

    Dim parts() As String = Regex.Split(",", Result)
    Dim cssWidth As Float = parts(0)
    Dim cssHeight As Float = parts(1)

    ' Calculate scale factor
    Dim b4xWidth As Float = newWebView.Width
    Dim scale As Float = cssWidth / b4xWidth

    ' Debug logs
    Log("cssWidth: " & cssWidth)
    Log("cssHeight: " & cssHeight)
    Log("b4xWidth (DIPs): " & b4xWidth)
    Log("scale: " & scale)
    Log("finalHeight (DIPs): " & (cssHeight / scale))

    ' Apply calculated height
    finalHeight = cssHeight / scale
    newWebView.Height = finalHeight
    xWebView1.Height = finalHeight
     
    #Else b4i
 
    ' Wait for page load on iOS
    Wait For newWebView_PageFinished (Success As Boolean, Url As String)
     
    ' Execute JavaScript to get content height
    wait for (newWebView.EvaluateJavaScript("document.documentElement.scrollHeight")) newWebView_JSComplete (Success As Boolean, Result As String)
     
    If Success Then
        finalHeight = DipToCurrent(Result)
        newWebView.Height = finalHeight
        xWebView1.Height = finalHeight
    End If
     
    #End If
 
    #if b4a
    newWebView.RemoveView
    #else if b4i
    newWebView.RemoveViewFromParent
    #End If
 
    CallSubDelayed2(xCallback1,"loadHtmlAndResizeComplete", finalHeight)
End Sub
'-------------------------------------------------------------------

#End Region

pPage2
pPage2:
Sub Class_Globals
    Private Root As B4XView 'ignore
    Private xui As XUI 'ignore

    ' List of HTML texts to display
    Private Texts As List
 
    ' Main WebViews displayed on screen
    Private WebView1 As WebView
    Private WebView2 As WebView
End Sub

Public Sub Initialize As Object
    Return Me
End Sub

Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
     
    ' Load layout
    Root.LoadLayout("Page2")
 
    #if b4i
    ' Wait for resize event on iOS before continuing
    Wait For B4XPage_Resize (Width As Int, Height As Int)
    #End If
 
    ' Initialize list of sample texts
    Texts.Initialize

    ' Add multiple HTML samples (student behavior reports)
    Texts.Add("<p>Hello</p><p>Lucas participated well in today's activity and interacted with his classmates.</p>")
    Texts.Add("<p>Hello</p><p>Maria had difficulty concentrating today, getting up several times during class.</p>")
    Texts.Add("<p>Hello</p><p>Pedro showed calm behavior, completed the proposed activities, and helped his classmates.</p>")
    Texts.Add("<p>Hello</p><p>Julia was very agitated today, ran around the classroom, pushed classmates, and had difficulty following instructions. She required several interventions from the teacher.</p>")
    Texts.Add("<p>Hello</p><p>Gabriel had a productive day. He participated in activities, responded well to instructions, and showed interest.</p>")
    Texts.Add("<p>Hello</p><p>Ana showed challenging behavior today. She refused to participate in activities, shouted at times, and needed to be removed from the classroom to calm down. After some time, she returned calmer.</p>")
    Texts.Add("<p>Hello</p><p>Rafael showed significant progress today. He was able to stay focused longer and interacted positively with classmates during group activities.</p>")
    Texts.Add("<p>Hello</p><p>Beatriz was restless for most of the period. She ran around the classroom, tried to climb on furniture, and had difficulty respecting limits. She was redirected several times.</p>")
    Texts.Add("<p>Hello</p><p>Matheus had excellent behavior today. He participated in all activities, respected his classmates, and followed instructions independently.</p>")
    Texts.Add("<p>Hello</p><p>Carla showed mixed behavior today. At times she participated well, but at others she became agitated, pushed classmates, and had difficulty controlling her emotions. We reinforced the importance of discussing this at home.</p>")
    Texts.Add("<p>Hello</p><p>Bruno was attentive during most of the class and completed his tasks with minimal assistance.</p>")
    Texts.Add("<p>Hello</p><p>Fernanda showed improvement in following instructions and staying seated during activities.</p>")
    Texts.Add("<p>Hello</p><p>Diego had some difficulty sharing materials with classmates but responded well after guidance.</p>")
    Texts.Add("<p>Hello</p><p>Larissa participated in group activities and demonstrated good teamwork skills.</p>")
    Texts.Add("<p>Hello</p><p>Eduardo was distracted at times but managed to complete his activities with encouragement.</p>")
    Texts.Add("<p>Hello</p><p>Camila was calm and cooperative, following classroom rules appropriately.</p>")
    Texts.Add("<p>Hello</p><p>Matheus had excellent behavior today. He participated in all activities with great enthusiasm, respected his classmates, and followed instructions independently. He also demonstrated responsibility by organizing his materials and helping maintain a positive classroom environment. His interaction with peers was respectful and cooperative throughout the day.</p>")
    Texts.Add("<p>Hello</p><p>Julia showed a positive attitude during today's activities. Although she needed a few reminders to stay focused, she was able to complete her tasks successfully. She interacted well with her classmates and showed kindness during group work. We encourage her to continue improving her concentration and maintaining this positive behavior.</p>")
    Texts.Add("<p>Hello</p><p>Gabriel had a productive day overall. He actively participated in class discussions and showed interest in the proposed activities. At times, he became slightly distracted, but responded well to guidance. He demonstrated good problem-solving skills and worked well both independently and in groups.</p>")
    Texts.Add("<p>Hello</p><p>Maria had some challenges today with maintaining focus during longer activities. She needed frequent redirection and support from the teacher. However, she showed improvement as the day progressed and was able to complete part of her work. It is important to continue reinforcing routines and encouraging her engagement.</p>")
    Texts.Add("<p>Hello</p><p>Lucas demonstrated great progress today. He remained focused for longer periods, followed instructions carefully, and completed all assigned activities. He also interacted positively with classmates and showed respect for classroom rules. We are very pleased with his development.</p>")
    Texts.Add("<p>Hello</p><p>Beatriz showed moments of restlessness during the class. She had difficulty staying seated and following some instructions, requiring several reminders. Despite this, she was able to participate in certain activities and showed willingness to improve. Continued support and reinforcement at home would be beneficial.</p>")
    Texts.Add("<p>Hello</p><p>Rafael had an excellent day. He demonstrated autonomy in completing his tasks, helped classmates when needed, and followed all instructions without difficulty. His behavior was exemplary, and he contributed positively to the classroom environment.</p>")
    Texts.Add("<p>Hello</p><p>Ana presented mixed behavior today. During some periods, she was focused and participated actively. However, at other times she became distracted and had difficulty managing her emotions. With support, she was able to regain control and continue her activities. We recommend reinforcing emotional regulation strategies.</p>")
 
    ' Trigger initial load
    Panel1_Click
End Sub

Sub B4XPage_Appear
End Sub

Private Sub Panel1_Click
 
    Dim html As String = ""
 
    ' Select random text
    html = Texts.Get(Rnd(0, Texts.Size))
 
    ' Load and resize first WebView
    B4XPages.MainPage.loadHtmlAndResize2(Me, Root, WebView1, html)
    Wait For loadHtmlAndResizeComplete(Height1 As Int)
 
    '-------------------------
 
    ' Position second WebView below the first
    WebView2.Top = ((WebView1.Top + WebView1.Height) + 20dip)
 
    ' Select another random text
    html = Texts.Get(Rnd(0, Texts.Size))
 
    ' Load and resize second WebView
    B4XPages.MainPage.loadHtmlAndResize2(Me, Root, WebView2, html)
    Wait For loadHtmlAndResizeComplete(Height1 As Int)
 
End Sub

pPage3
pPage3:
Sub Class_Globals
    Private Root As B4XView 'ignore
    Private xui As XUI 'ignore

    ' List of HTML texts to display
    Private Texts As List
 
    ' Main WebViews displayed on screen
    Private WebView1Item As WebView
    Private WebView2Item As WebView
    Private Panel1Item As B4XView
    Private Label1Item As B4XView
 
    Private clvBackground As CustomListView
End Sub

Public Sub Initialize As Object
    Return Me
End Sub

Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
     
    ' Load layout
    Root.LoadLayout("Page3")
 
    #if b4i
    ' Wait for resize event on iOS before continuing
    Wait For B4XPage_Resize (Width As Int, Height As Int)
    #End If
 
    ' Initialize list of sample texts
    Texts.Initialize

    ' Add multiple HTML samples (student behavior reports)
    Texts.Add("<p>Hello</p><p>Lucas participated well in today's activity and interacted with his classmates.</p>")
    Texts.Add("<p>Hello</p><p>Maria had difficulty concentrating today, getting up several times during class.</p>")
    Texts.Add("<p>Hello</p><p>Pedro showed calm behavior, completed the proposed activities, and helped his classmates.</p>")
    Texts.Add("<p>Hello</p><p>Julia was very agitated today, ran around the classroom, pushed classmates, and had difficulty following instructions. She required several interventions from the teacher.</p>")
    Texts.Add("<p>Hello</p><p>Gabriel had a productive day. He participated in activities, responded well to instructions, and showed interest.</p>")
    Texts.Add("<p>Hello</p><p>Ana showed challenging behavior today. She refused to participate in activities, shouted at times, and needed to be removed from the classroom to calm down. After some time, she returned calmer.</p>")
    Texts.Add("<p>Hello</p><p>Rafael showed significant progress today. He was able to stay focused longer and interacted positively with classmates during group activities.</p>")
    Texts.Add("<p>Hello</p><p>Beatriz was restless for most of the period. She ran around the classroom, tried to climb on furniture, and had difficulty respecting limits. She was redirected several times.</p>")
    Texts.Add("<p>Hello</p><p>Matheus had excellent behavior today. He participated in all activities, respected his classmates, and followed instructions independently.</p>")
    Texts.Add("<p>Hello</p><p>Carla showed mixed behavior today. At times she participated well, but at others she became agitated, pushed classmates, and had difficulty controlling her emotions. We reinforced the importance of discussing this at home.</p>")
    Texts.Add("<p>Hello</p><p>Bruno was attentive during most of the class and completed his tasks with minimal assistance.</p>")
    Texts.Add("<p>Hello</p><p>Fernanda showed improvement in following instructions and staying seated during activities.</p>")
    Texts.Add("<p>Hello</p><p>Diego had some difficulty sharing materials with classmates but responded well after guidance.</p>")
    Texts.Add("<p>Hello</p><p>Larissa participated in group activities and demonstrated good teamwork skills.</p>")
    Texts.Add("<p>Hello</p><p>Eduardo was distracted at times but managed to complete his activities with encouragement.</p>")
    Texts.Add("<p>Hello</p><p>Camila was calm and cooperative, following classroom rules appropriately.</p>")
    Texts.Add("<p>Hello</p><p>Matheus had excellent behavior today. He participated in all activities with great enthusiasm, respected his classmates, and followed instructions independently. He also demonstrated responsibility by organizing his materials and helping maintain a positive classroom environment. His interaction with peers was respectful and cooperative throughout the day.</p>")
    Texts.Add("<p>Hello</p><p>Julia showed a positive attitude during today's activities. Although she needed a few reminders to stay focused, she was able to complete her tasks successfully. She interacted well with her classmates and showed kindness during group work. We encourage her to continue improving her concentration and maintaining this positive behavior.</p>")
    Texts.Add("<p>Hello</p><p>Gabriel had a productive day overall. He actively participated in class discussions and showed interest in the proposed activities. At times, he became slightly distracted, but responded well to guidance. He demonstrated good problem-solving skills and worked well both independently and in groups.</p>")
    Texts.Add("<p>Hello</p><p>Maria had some challenges today with maintaining focus during longer activities. She needed frequent redirection and support from the teacher. However, she showed improvement as the day progressed and was able to complete part of her work. It is important to continue reinforcing routines and encouraging her engagement.</p>")
    Texts.Add("<p>Hello</p><p>Lucas demonstrated great progress today. He remained focused for longer periods, followed instructions carefully, and completed all assigned activities. He also interacted positively with classmates and showed respect for classroom rules. We are very pleased with his development.</p>")
    Texts.Add("<p>Hello</p><p>Beatriz showed moments of restlessness during the class. She had difficulty staying seated and following some instructions, requiring several reminders. Despite this, she was able to participate in certain activities and showed willingness to improve. Continued support and reinforcement at home would be beneficial.</p>")
    Texts.Add("<p>Hello</p><p>Rafael had an excellent day. He demonstrated autonomy in completing his tasks, helped classmates when needed, and followed all instructions without difficulty. His behavior was exemplary, and he contributed positively to the classroom environment.</p>")
    Texts.Add("<p>Hello</p><p>Ana presented mixed behavior today. During some periods, she was focused and participated actively. However, at other times she became distracted and had difficulty managing her emotions. With support, she was able to regain control and continue her activities. We recommend reinforcing emotional regulation strategies.</p>")
 
    ' Trigger initial load
    Panel1_Click
End Sub

Sub B4XPage_Appear
End Sub

Private Sub Panel1_Click
    Dim html As String = ""
 
    clvBackground.Clear
 
    For i = 1 To 10
         
        Dim pnlItem As B4XView = xui.CreatePanel(Null)
        pnlItem.SetLayoutAnimated(0, 0, 0, clvBackground.AsView.Width, 700dip)
        pnlItem.LoadLayout("Page3Item")
         
        Label1Item.Text = "Label1 -> " & i
     
        ' Select random text
        html = Texts.Get(Rnd(0, Texts.Size))
         
        ' Load and resize second WebView
        B4XPages.MainPage.loadHtmlAndResize2(Me, Root, WebView1Item, html)
        Wait For loadHtmlAndResizeComplete(Height1 As Int)
     
        '-------------------------
 
        ' Position second WebView below the first
        WebView2Item.Top = ((WebView1Item.Top + WebView1Item.Height) + 20dip)
     
        ' Select random text
        html = Texts.Get(Rnd(0, Texts.Size))
         
        ' Load and resize second WebView
        B4XPages.MainPage.loadHtmlAndResize2(Me, Root, WebView2Item, html)
        Wait For loadHtmlAndResizeComplete(Height1 As Int)
     
        ' Position second WebView below the first
        Panel1Item.Height = ((WebView2Item.Top + WebView2Item.Height) + 20dip)
        pnlItem.Height = Panel1Item.Height
     
        clvBackground.Add(pnlItem, i)
         
    Next
 
    If clvBackground.Size = 0 Then
        clvBackground.AddTextItem("no record", Null)
    End If
 
End Sub

1774015623808.png
1774015646618.png
1774015664621.png
 

Attachments

  • teste_webview_altura.zip
    195.7 KB · Views: 5
Last edited:
Top