Android 简单实现View自动换行(附源码)

发布时间:2019-06-13 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Android 简单实现View自动换行(附源码)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

hi,
尘少又来了,
这次为大家带来的,
是View可以自动换行的容器。

类似于淘宝搜索时的推荐,
首先我不知道淘宝的是否只支持文字,
但是我的是任何View都支持的。
看下效果先:

淘宝:
Bamboy自动换行——淘宝

我的:
Bamboy自动换行

废话不多少,
上代码:
1、先把我的自定义控件放到你的项目里

Android 简单实现View自动换行(附源码)

2、ActivITy的XML布局
如果里边放很多条目的话,
可能要套在ScrollView里,
显示不全

<ScrollView
    andROId:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.bamboy.autowordwrap.BamAutoLineList
        android:id="@+id/bal_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp" />
</ScrollView>

3、条目的XML
我的条目是图片+文字的,
所以我的XML是这样的:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout >"http://schemas.android.COM/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/BTn_padding"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="10dp">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon" />

    <TextView
        android:id="@+id/tv_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="条目条目条目"
        android:textSize="14sp" />
</LinearLayout>

这里有一点需要说声抱歉,
因为这是自动换行控件,
所以我的设定是:

条目的XML最外层的Layout,
高只能是wrap_content,
即使你设置成match_parent,
或者指定多少dp,
都是无效的。
连设置margin也都是无效。

如果你确实需要限制宽高,
那你可以多套一层Layout,
在内层Layout设置即可。

4、Activity代码

PRivate Button btn_add;
private BamAutoLineList bal_list;

@override
protected void onCreate(Bundle savedInstancestate) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn_add = (Button) findViewById(R.id.btn_add);
    bal_list = (BamAutoLineList) findViewById(R.id.bal_list);

    // 点击事件
    btn_add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // 实例化View
            View item = getLayoutInflater().inflate(R.layout.item, null);
            // 把View放到控件里去
            bal_list.addView(item);
        }
    });
}

到此就结束了,
尘少一贯的风格,
就是这么简单

尘少老规矩,
码:
http://download.csdn.net/down...

如果觉得尘少的Demo还不错的话,
可以克隆我的Git仓库,
各种酷炫效果收入囊中:
https://github.com/Bamboy1203...
手机扫码下载App一睹为快:

Android 简单实现View自动换行(附源码)

脚本宝典总结

以上是脚本宝典为你收集整理的Android 简单实现View自动换行(附源码)全部内容,希望文章能够帮你解决Android 简单实现View自动换行(附源码)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。