以编程方式重新应用layout_centerHorizo​​ntal

时间:2015-03-21 01:18:58

标签: android android-layout

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

<?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="$10"
    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);
}

....

1 个答案:

答案 0 :(得分:0)

将layout_width和layout_height更改为&#34; match_parent&#34;