最近有个需求是在布局上动态添加view,本来想写死的,但是发现这样写,后期如果需求变动后改动很大,不灵活,还得重新写,于是研究了一下在布局上动态添加view的方式。
1.初始化View:
2.初始化事件监听
3.向容器中添加TextView
/**
* 按钮点击事件,向容器中添加TextView
* @param view
*/
public void addView(View view) {
TextView child = new TextView(this);
child.setTextSize(20);
child.setTextColor(getResources().getColor(R.color.colorAccent));
child.setText("找到很多女朋友");
// 调用一个参数的addView方法
llContent.addView(child);
}
4.添加一个布局.
.
5.移除最后一个View:
//根据view的数量移除最后一个
View view = llContent.getChildAt(llContent.getChildCount() - 1);
llContent.removeView(view);
6.布局文件activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="@color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_add"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="addView"
android:textColor="@color/colorPrimaryDark"
android:textSize="16sp"
android:gravity="center"/>
<TextView
android:id="@+id/tv_dynamic_add"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_gravity="bottom"
android:text="addDynamicView"
android:textColor="@color/colorPrimaryDark"
android:textSize="16sp"
android:gravity="center"/>
<TextView
android:id="@+id/tv_remove"
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center"
android:text="removeView"
android:textSize="16sp"
android:textColor="@color/colorPrimaryDark" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher"
android:layout_gravity="center"
android:layout_marginTop="20dp"/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
7.实现的效果如下:
8.做项目需求时不仅仅是实现功能,还要考虑性能和后期的扩展性,盲目的写代码,只会让项目越来越乱,扩展和灵活性很差,如果时间允许的情况下,可以考虑多种方案,找到一个合适的》其实博主的需求就是在发布商品时添加6个规格,当然这个还可以用recyclerview实现,根据item的数量来实时动态显示view.写得不好,小伙伴们如有更好地方案,可以给我留言,我会吸取各种好的建议,当然有问题也可以提出来,我及时更正.
最后,项目的完整地址如下:gitee.com/jackning_ad…