以编程方式重新应用 layout_centerHorizontal

Re-apply layout_centerHorizontal programmatically

我有一个自定义的相对布局视图,我必须在其中动态更改背景资源。问题是,设置背景后,其子项的 layout_centerHorizontal 属性 被删除,项目不再水平居中。我想弄清楚如何重新应用它。这是我的布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/marker_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:background="@drawable/ic_markerdefault"
>

<ImageView
    android:id="@+id/marker_category"
    android:layout_width="20dp"
    android:layout_height="20dp"
    tools:src="@drawable/ic_bike"
    android:layout_centerHorizontal="true"
    />

<TextView
    android:id="@+id/marker_price"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/marker_category"
    tools:text=""
    android:layout_centerHorizontal="true"
    style="@style/MarkerPriceText"

    />
</RelativeLayout>

代码:

private ImageView mImgCategory;
private TextView mTextPrice;
...

private void setBackground(int state) {


    switch (state) {
        case DEFAULT:
            this.setBackgroundResource(R.drawable.ic_markerdefault);
            break;
        case ACTIVE:
            this.setBackgroundResource(R.drawable.ic_markerselected);
            break;
        case VISITED:
            this.setBackgroundResource(R.drawable.ic_markervisited);
            break;
        default:
            this.setBackgroundResource(R.drawable.ic_markerdefault);
            break;
    }

    RelativeLayout.LayoutParams lp = (LayoutParams) mImgCategory.getLayoutParams();
    lp.addRule(RelativeLayout.CENTER_HORIZONTAL, TRUE);
    mImgCategory.setLayoutParams(lp);

    RelativeLayout.LayoutParams lp2 = (LayoutParams) mTextPrice.getLayoutParams();
    lp2.addRule(CENTER_HORIZONTAL, TRUE);
    mTextPrice.setLayoutParams(lp2);
}

....

将layout_width和layout_height更改为"match_parent"