Sony
Sony

Reputation: 7196

Custom view on measure not working as expected

I am creating a custom TextView which can draw text at both ends like this,and this supports multiline, so that the number of text views can be cut down to half(I got a lint warning, complaining about 80+ views, and most of the views are TextViews in my layout, like first name , last name added in a grid layout)

Please see the screen shot, this is the current state of the view

Screen shot

It will show the text when the height is fixed, i don't want this behavior because the text on the right can be of any length and it should wrap the height to the desired height. This is the overridden onMeasure method

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    if (mRightText == null) return;
    initStaticLayout();
    setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), mLayout.getHeight());
}

mLayout is a StaticLayout

private void initStaticLayout() {
    if (mLayout == null) {
        mLayout = new StaticLayout(mRightText, mPaint, 
                getWidth() / 2 - getPaddingRight() - getPaddingLeft(),
                Layout.Alignment.ALIGN_NORMAL, 
                1, 0, true);
    }
}

if the height is set to wrap_content it is not drawing anything.

Upvotes: 0

Views: 1496

Answers (2)

Sony
Sony

Reputation: 7196

When i tried the view in emulator, I got this exception as soon as the activity is launched,

java.lang.IllegalArgumentException: Layout: -xx < 0

that is from the initStaticLayout regarding the width

mLayout = new StaticLayout(mRightText, mPaint, 
                /*the error was here*/ getWidth() / 2 - getPaddingRight() - getPaddingLeft(),
                Layout.Alignment.ALIGN_NORMAL, 
                1, 0, true);

and i changed it from getWidth() to screenWidth and now i can wrap the height, no matter how big the right text is. I don't know why fixing a width issue fixed a height issue, may be because of the exception , the layout is not able to generate preview.

Thank you @pskink for the adb tip and thank you every one

Upvotes: 0

vinay
vinay

Reputation: 159

instead in xmlfile why can't you create two textviews keeping layout_weight as 1. so that entire screen will be divided into two equal partitions.

Upvotes: 0

Related Questions