gpt4 book ai didi

android:如何让js代码改变webview的大小

转载 作者:行者123 更新时间:2023-11-29 01:00:14 24 4
gpt4 key购买 nike

我正在使用 API 19(android4.4) 开发一个 android 应用程序。我有一个 linearLayout View 嵌套了另一个 linearLayout View 。现在我想通过js代码改变这个linearLayout的高度,但是它不起作用。

active_main.xml

<LinearLayout xmlns="...." ...
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@id/sContainer"
tools:context=".MainActivity">
</LinearLayout>

java测试代码:

...
private LinearLayout webViewContainer;
...
private void initView(){
LinearLayout container=(LinearLayout)findViewById(R.id.sContainer);
//add a child linearLayout
webViewContainer=new LinearLayout(this);
LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,200);
webViewContainer.setLayoutParams(layoutParams);
//add a child webview in this linearlayout
WebView webview=(WebView)new WebView(this);
LinearLayout.LayoutParams webParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
webview.setLayoutParams(webParams);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JsInteraction(), "bridge");
webView.loadUrl("http://xxxx/index.html");
webView.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url){
view.loadUrl("javascript:callHtml('show')");
}
});
webViewContainer.addView(webview);
container.addView(webViewContainer);
}


class JsInteraction{
@JavascriptInterface
public void expand(){
LinearLayout.LayoutParams layoutParams=webViewContainer.getLayoutParams();
layoutParams.height = 500;
webViewContainer.setLayoutParams(layoutParams);
Log.v("height", layoutParams.height+"");
}
}

index.html js代码

<script>
function callHtml(method){
case 'show':
setTimeout(function(){
bridge.expand();//call app to expand after 5s
},5000);
break;
}
</script>

日志显示 layoutParams.height 已更改为 500,但我的模拟器没有任何反应,我做错了什么?此外,如果我单击一个按钮来更改 layoutParams 的高度,它会起作用。

最佳答案

那是“可能”,因为您还没有调用 requestLayout这是在您进行布局更改后需要的( View 的布局失效)

Call this when something has changed which has invalidated the layout of this view. This will schedule a layout pass of the view tree. This should not be called while the view hierarchy is currently in a layout pass (isInLayout(). If layout is happening, the request may be honored at the end of the current layout pass (and then layout will run again) or after the current frame is drawn and the next layout occurs.

所以,在改变高度之后,你应该调用requestLayout...

linearLayout.requestLayout();

关于android:如何让js代码改变webview的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51737602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com