Java 无法在RelativeLayout中居中查看

Java 无法在RelativeLayout中居中查看,java,android,android-layout,android-relativelayout,Java,Android,Android Layout,Android Relativelayout,我正在尝试将视图置于父视图的中心RelativeLayout: private void addLoadingAnimation() { RelativeLayout mainView = (RelativeLayout) findViewById(R.id.medical_supply_tile_activity); mainView.removeAllViews(); GifView gifView = new GifView(this); RelativeL

我正在尝试将视图置于父视图的中心
RelativeLayout

private void addLoadingAnimation() {
    RelativeLayout mainView = (RelativeLayout) findViewById(R.id.medical_supply_tile_activity);
    mainView.removeAllViews();
    GifView gifView = new GifView(this);
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
    gifView.setId(R.id.loading_gif);
    mainView.setBackgroundColor(getResources().getColor(android.R.color.background_light));
    mainView.addView(gifView,layoutParams);
}
我还尝试添加了
layoutParams.addRule(RelativeLayout.ALIGN\u PARENT\u RIGHT,0)在父行的
居中之前。似乎什么都没用。它始终与右下角对齐

以下是我的家长观点:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/background_light"
    tools:context=".MedecineTileActivity"
    android:id="@id/medical_supply_tile_activity"
    android:layout_gravity="left">    
</RelativeLayout>


gravity=left
是因为当加载的动画被删除时,我插入片段并希望它们转到左侧。

我通过将子视图的右对齐父视图的右对齐,并将子视图的左对齐父视图的左对齐来实现这一点

<TextView
            style="@style/NewTextM2"
            android:id="@+id/soft_dialog_info_item_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/<Parent>"
            android:layout_alignLeft="@+id/<Parent>"
            android:layout_alignRight="@+id/<Parent>"
            android:gravity="center"
            android:tag="item_text"
            android:text="@string/text"
            android:maxLines="1" />

这将使视图与父视图的底部中心对齐。

在您的
相对视图中添加
android:gravity=“center”