views:

146

answers:

1

Hi,
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  A: 

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.

Mathias Lin
I have updated the question with code. Gravity is working fine, the webView gets centered with it. Is there any way to restrict its size i.e. to 300x200 irrespective of loading page size, and rest of the content should get cropped or horizontal/vertical scrollbars can be shown. Thanks!
bhups
yes, you can do that via setLayoutParams, either for the surrounding LinearLayout or the WebView itself; instead of using ViewGroup.LayoutParams.FILL_PARENT:LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(300, 200);ll.setLayoutParams( params);
Mathias Lin