0

我正在基于从服务器接收到的 JSON 以编程方式创建我的控件。我需要创建的控件之一WebView是在屏幕上水平居中的控件。这在 xml 布局中很简单,如下所示,使用 layout_gravity 选项。但是你如何在代码中做到这一点,就像没有方法WebView一样。TextViewsetGravity(Gravity.HORIZONTAL_GRAVITY_MASK)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<WebView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"/>

</LinearLayout>
4

2 回答 2

2

我会使用RelativeLayout,然后您可以在添加视图时使用LayoutParams:

RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 1);
relativeLayout.addView(yourWebView, layoutParams);
于 2012-06-06T16:30:32.020 回答
0

我使用 LinearLayout 来显示 webview 和 setGravity。

       LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.FILL_PARENT));
    linearLayout.setGravity(Gravity.CENTER);
    WebView view = new WebView(this);
    linearLayout.addView(view);
    setContentView(linearLayout);

它可以帮助你。

于 2012-06-06T16:55:11.627 回答