Question

I have this layout

<RelativeLayout
        android:id="@+id/gameportView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <com.pepotegames.spotthedifferences.DifferenceView
            android:id="@+id/imageA"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/progressBar1"
            android:layout_centerHorizontal="true" />

        <ProgressBar
            android:id="@+id/progressBar1"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="16dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:max="1000"
            android:progress="0" />

        <com.pepotegames.spotthedifferences.DifferenceView
            android:id="@+id/imageB"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/progressBar1"
            android:layout_centerHorizontal="true" />

    </RelativeLayout>

As you can see, imageA and imageB are positioned relative to my ProgressBar. The problem is that I need to resize the ProgressBar at runtime. For that I have a custom listener that gets triggered when my custom View onSizeChanged method gets called.

imageA.setOnSizeChangedLister(new DifferenceView.OnSizeChangedListener(){
        @Override
        public void onResize(){
            level.scaleBy(imageA.getScale());

            bar.setLayoutParams(new RelativeLayout.LayoutParams(imageA.getWidth(),bar.getHeight()));
        }
    });

Everything works fine except that im passing a set of new LayoutParams to my bar. So, how can I resize that progressbar without losing the android:layout_centerHorizontal="true" and android:layout_centerVertical="true" attributes?

Was it helpful?

Solution

Use the following -

imageA.setOnSizeChangedLister(new DifferenceView.OnSizeChangedListener(){
    @Override
    public void onResize(){
        level.scaleBy(imageA.getScale());

        RelativeLayout.LayoutParams existingLayoutParams = ((RelativeLayout.LayoutParams) bar.getLayoutParams());
        existingLayoutParams.width = imageA.getWidth();
        existingLayoutParams.height = imageA.getHeight();
        bar.setLayoutParams(existingLayoutParams);
    }
});

OTHER TIPS

Instead of creating a new LayoutParams, try extracting the current LayoutParams of the View using getLayoutParams and then edit the desirable values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top