Java 以编程方式居中放置WebView

Java 以编程方式居中放置WebView,java,android,layout,webview,Java,Android,Layout,Webview,我正在基于从服务器接收的JSON以编程方式创建控件。我需要创建的控件之一是WebView,它在屏幕上水平居中。这在xml布局中很简单,如下所示,使用layout_gravity选项。但是如何在代码中做到这一点,WebView与TextView不同,它没有setGravity(Gravity.HORIZONTAL\u Gravity\u MASK)方法 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:andro

我正在基于从服务器接收的JSON以编程方式创建控件。我需要创建的控件之一是
WebView
,它在屏幕上水平居中。这在xml布局中很简单,如下所示,使用layout_gravity选项。但是如何在代码中做到这一点,
WebView
TextView
不同,它没有
setGravity(Gravity.HORIZONTAL\u Gravity\u 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>

我将使用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);

我使用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);

它可以帮助您。

也许布局参数和规则可以帮助您?我到家后去看看。干杯谢谢,但我已经试过了。我添加视图的页面是一个线性布局,它填充了可用空间。因此,我将web视图包装成一个线性布局,并设置重力。然后将该线性布局添加到主布局。这对webview的发布没有影响。不像我在下面的帖子上的评论,我没有机会尝试。但是您必须在父级中使用“中心”吗?您认为这是否会起作用,因为相对布局被添加到主布局的子级,而主布局是一个线性布局。如果相对布局的宽度/高度设置为“填充父级”,并且WebView设置为“相对布局内的centerInParent”,则WebView将在相对布局中居中,因此以线性布局为中心。虽然,如果你只有一个LinearLayout和一个WebView,我会完全放弃LinearLayout,只是将其更改为一个RelativeLayout,因为两者都是不必要的。这也不起作用。唯一使其居中的方法是在layourParams中指定宽度/高度,但由于我无法事先计算出宽度/高度,我放弃了,并将webview的宽度设置为与屏幕宽度相同。如果希望它成为屏幕的宽度,则需要使用fill\u parent,使用fill\u parent部分编辑主帖子