Preface: After entering the society, there are a lot of things have become involuntarily, such as overtime, a week before the holiday are in the state of overtime, overtime to overtime, but the problem or have to record, not to say more, directly above:

I believe most people have encountered such a requirement, the title of an Item followed by a label, can only display one line, and the label is the first need to display, that is to say, the label must display completely, and then the title as much as possible to display text, if not enough one line.Instead. All right, let’s break it down:

In particular, many people prefer to have the label displayed on the right side and the title on the left side of the label to occupy the rest of the layout. When the title and label text are too short to be placed next to each other, this will not work. Others might think, using linear layout, adaptive, tag title set weight, doing so may be the consequences of the same as above, when a headline is very short, can’t words on each side next to each other, finally believe most people will choose to let the UI to shit, what design of X, but people are realized the designer would say IOS, You should be able to implement Android ah! WTF!!!!!! Scold after still have to obediently give it to realize, this is the life of the program ape!

Truth: * * * * after complaints, let’s think about what do you have any solution, the first thing I thought of a dynamic to title set space, make label layout first, and then calculate out the label the amount of space, there are some other margin of what, to calculate the width of the screen, then minus the tags and margin of the space, the rest is the title of the space. So how do we calculate the text width?

Method for obtaining text width:

TextPaint textPaintTitle=tvTitle.getPaint(); / / title text is shown on the textview int textTitleWidth = (int) textPaintTitle. MeasureText (title);Copy the code

To get the width of the TextView:

private void setText() { tvTitle.setText(title); tvLabel.setText(label); textPaintTitle = tvTitle.getPaint(); textPaintLabel = tvLabel.getPaint(); int screenWidth = ScreenUtil.getScreenWidth(this); int textTitleWidth = (int) textPaintTitle.measureText(title); int textLabelWidth = (int) textPaintLabel.measureText(label); // This 60dp is some margin of textView and so on, Int totalLeaveWidth = screenWidth-textLabelWidth-screenUtil.dp2px (this, 60.0f); if (textTitleWidth > totalLeaveWidth) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tvTitle.getLayoutParams(); params.width = totalLeaveWidth; }}Copy the code

This can solve the above problems: