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

来源:互联网 发布:js 日程安排插件 编辑:程序博客网 时间:2024/04/20 02:44

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

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

我的:
Bamboy自动换行

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

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 xmlns:android="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;@Overrideprotected 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/download/bamboy_/9737021

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

0 0
原创粉丝点击