当前位置:   article > 正文

Android 两个view并列显示_view并排

view并排

两个view并列显示,第二个view跟在第一个view的后面,如果长度过长,则第一个view宽度缩小。

直接上代码  用就完了!

  1. public class TextWithImageLayout extends LinearLayout {
  2. private final int MARGIN = 40;
  3. private int mMargin;
  4. private int[] mChildWidthList;
  5. public TextWithImageLayout(Context context, AttributeSet attrs) {
  6. super(context, attrs);
  7. mMargin = MARGIN;
  8. }
  9. @Override
  10. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  11. super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  12. int widthSize = MeasureSpec.getSize(widthMeasureSpec);
  13. int heightSize = MeasureSpec.getSize(heightMeasureSpec);
  14. int count = getChildCount();
  15. View firstChild = getChildAt(0);
  16. if (count > 1) {
  17. int firstChildWidth = firstChild.getMeasuredWidth();
  18. int firstChildHeight = firstChild.getMeasuredHeight();
  19. int otherChildrenWidth = 0;
  20. int otherChildrenHeight = 0;
  21. for (int i = 1; i < count; i++) {
  22. View child = getChildAt(i);
  23. int width;
  24. if (mChildWidthList == null) {
  25. width = child.getMeasuredWidth();
  26. } else {
  27. width = mChildWidthList[i - 1];
  28. }
  29. otherChildrenWidth += width;
  30. child.measure(width | MeasureSpec.EXACTLY, child.getMeasuredHeight() | MeasureSpec.EXACTLY);
  31. otherChildrenHeight = child.getMeasuredHeight();
  32. }
  33. int margin = mMargin * (count - 1);
  34. if (firstChildWidth + otherChildrenWidth + margin > widthSize) {
  35. firstChildWidth = widthSize - otherChildrenWidth - margin;
  36. }
  37. heightSize = firstChildHeight > otherChildrenHeight ? firstChildHeight : otherChildrenHeight;
  38. firstChild.measure(firstChildWidth | MeasureSpec.EXACTLY,
  39. firstChildHeight | MeasureSpec.EXACTLY);
  40. } else {
  41. firstChild.measure(firstChild.getMeasuredWidth(), firstChild.getMeasuredHeight());
  42. heightSize = firstChild.getMeasuredHeight();
  43. }
  44. setMeasuredDimension(widthSize, heightSize);
  45. }
  46. @Override
  47. protected void onLayout(boolean changed, int l, int t, int r, int b) {
  48. super.onLayout(changed, l, t, r, b);
  49. int count = getChildCount();
  50. int left = 0;
  51. for (int i = 0; i < count; i++) {
  52. final View child = this.getChildAt(i);
  53. int width = child.getMeasuredWidth();
  54. int height = child.getMeasuredHeight();
  55. int top = (b - t) / 2 - height / 2;
  56. child.layout(left, top, left + width, top + height);
  57. left = left + width + mMargin;
  58. }
  59. }
  60. public int[] getChildWidthList() {
  61. return mChildWidthList;
  62. }
  63. public void setChildWidthList(int[] childWidthList) {
  64. this.mChildWidthList = childWidthList;
  65. }
  66. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/242712
推荐阅读
相关标签
  

闽ICP备14008679号