how to show a webview inside an activity in the middle of screen

◇◆丶佛笑我妖孽 提交于 2019-12-08 11:29:57

问题



I am having issue while showing a WebView in an activity in the middle of the screen. I have an activity and I want to show a webview in the center of screen. My activity is transparent so background activity will be visible. Whenever I try to create a webview and add it to activity using setContentView(webview) it always shows the view on the top left corner of the screen. Is their a way to workaround this?I am trying to do this via pure code only. Here is my code.

protected void onCreate(Bundle savedInstance) {
    //some initialization stuff
    LinearLayout ll = new LinearLayout(activity); 
    ll.setOrientation(LinearLayout.VERTICAL);
    ll.setGravity(Gravity.CENTER_HORIZONTAL);
    ll.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 
                        ViewGroup.LayoutParams.FILL_PARENT));
    ll.setBackgroundColor(android.R.color.transparent);
    ll.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL); //added after suggestion
    webView = new WebView(this);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.loadUrl("http://www.google.com");
    ll.addView(webView);
    webView.setBackgroundColor(android.R.color.transparent);
    setContentView(ll);
}
.

回答1:


setContentView(webview) is not possible, are you sure you're passing the webView here as param? It should be an id to a layout resource. Or do you mean addView?

You should place the WebView in a layout resource and add the layout_gravity attributes, to

layout_gravity="center_horizontal|center_vertical"

and/or the surrounding linearLayout or whatever you use to:

gravity="center_horizontal|center_vertical"

Please provide your code for more clarification.



来源:https://stackoverflow.com/questions/3369196/how-to-show-a-webview-inside-an-activity-in-the-middle-of-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!