hierarchy viewer makes height changes appear

2020-05-05 04:32发布

问题:

it's my first question.

I have built a custom component: a RelativeLayout with a TextView on the bottom and two ImageView above that, acting as a 2-columns clickable element of an histogram. To set the height of a bar, i get the "available height" in onLayout(), as container's height minus label's one:

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);
    mAvailHeight = getHeight()-findViewById(R.id.label).getHeight(); // it works

and then assign it (multiplied by a 0.-1. value) as a layout parameter to the ImageView:

    View bar = findViewById(R.id.bigBar);
    RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) bar.getLayoutParams();
    rlp.height = Math.round((float)mAvailHeight * mBigBarHeight);
}

The mBigBarHeight variable (0.-1.) can be set via this function:

public void setBigBarHeight(float value, float max) {
    mBigBarHeight = value / max;    
    requestLayout(); //
    invalidate();    // do these help? i find no difference
}

Now. When i add one of these "HistogramBar" in onCreate() and set the heights and label everything works as I expect. If i try to modify them later, say onClickSomething:

bar.setBigBarHeight(25, 100);
bar.setSmallBarHeight(50, 100);
bar.setLabel("jjk");

only the label changes. I checked with Hierarchy Viewer and actually the LayoutParams did change. If i click again changes appear.

The funny thing is that even if i do "Load View Hierarchy" from the tool changes get displayed (on the emulator)!! What happens? Is it strange? I want to do that in my code so that it works!

I couldn't find any similar question. Thanks.

回答1:

When you load a hierarchy from the tool, a relayout/redraw happens to measure performance. You are probably not calling requestLayout() when you should.