android自动换行的线性布局

android自动换行的线性布局

2023年7月13日发(作者:)

android⾃动换⾏的线性布局在项⽬中,有时候会有“横向排列,排满后⾃动换⾏”的需求(⽐如下图),要是⼦view是定长的就没什么好说的了,但如果是变长的话呢?这篇博客会帮你应对这种需求。 基本思路1. 最外层⼀层竖直线性布局(我们称为⽗布局)2. 新建⽔平线性布局(我们称为⾏布局)3. 计算待放⼊的view的宽度和⾏布局的剩下宽度4. 判断是否可以放⼊

(1). 若view的宽度⼩于等于剩余宽度,放⼊,到第三步;

(2). 若view的宽度⼤于剩余宽度,添加⾏布局到⽗布局,到第⼆步。

注意这⾥要注意⼏点:

1. ⼦view的宽度要加上间隔;

2. 若是⼦view的宽度⼤于⾏布局的宽度,不考虑对⼦view进⼊换⾏,直接放⼊;

接下来看代码,注释已经很详细,就不累赘了。

1. activity的布局 2. ⼦view3. ⼦view的背景 4. activity代码public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { te(savedInstanceState); setContentView(ty_main); initData(); ll_parent = (LinearLayout) findViewById(_parent); initAutoLL(); } // 数据 ArrayList datas = new ArrayList<>(); // 初始化数据 private void initData() { ("作 家"); ("段 ⼦ ⼿"); ("软 ⽂ 作 者"); ("摄 影 爱 好 者"); ("画 家"); ("画 家"); ("哦 我还很喜欢⾳乐"); ("还 有 其 他 七 七 ⼋ ⼋ 的 我 就 不 说 了"); ("⽼ 师"); } // 最外层的竖直线性布局 private LinearLayout ll_parent; // 绘制⾃动换⾏的线性布局 private void initAutoLL() {// 每⼀⾏的布局,初始化第⼀⾏布局 LinearLayout rowLL = new LinearLayout(this); Params rowLP =

new Params(_PARENT,

_CONTENT); float rowMargin = dipToPx(10); gins(0, (int) rowMargin, 0, 0); outParams(rowLP); boolean isNewLayout = false; float maxWidth = getScreenWidth() - dipToPx(30);// 剩下的宽度 float elseWidth = maxWidth; Params textViewLP =

new Params(_CONTENT,

_CONTENT); gins((int) dipToPx(8), 0, 0, 0); for (int i = 0; i < (); i++) {// 若当前为新起的⼀⾏,先添加旧的那⾏// 然后重新创建布局对象,设置参数,将isNewLayout判断重置为false if (isNewLayout) { ll_w(rowLL); rowLL = new LinearLayout(this); outParams(rowLP); isNewLayout = false; }// 计算是否需要换⾏ TextView textView = (TextView) getLayoutInflater().inflate(ew, null); t((i)); e(0, 0);// 若是⼀整⾏都放不下这个⽂本框,添加旧的那⾏,新起⼀⾏添加这个⽂本框 if (maxWidth < suredWidth()) { ll_w(rowLL); rowLL = new LinearLayout(this); outParams(rowLP); w(textView); isNewLayout = true; continue; }// 若是剩下的宽度⼩于⽂本框的宽度(放不下了)// 添加旧的那⾏,新起⼀⾏,但是i要-1,因为当前的⽂本框还未添加 if (elseWidth < suredWidth()) { isNewLayout = true; i--;// 重置剩余宽度 elseWidth = maxWidth; continue; } else {// 剩余宽度减去⽂本框的宽度+间隔=新的剩余宽度 elseWidth -= suredWidth() + dipToPx(8); if (ldCount() == 0) { w(textView); } else { outParams(textViewLP); w(textView); } } } }// 添加最后⼀⾏,但要防⽌重复添加 ll_View(rowLL); ll_w(rowLL); } // dp转px private float dipToPx(int dipValue) { return imension(X_UNIT_DIP,

dipValue,

ources().getDisplayMetrics()); } // 获得评论宽度 private float getScreenWidth() { return ources().getDisplayMetrics().widthPixels; }}其中主要代码在initAutoLL函数内部,运⾏后便可看到⽂章开头处的效果图

发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1689212595a221800.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信