Android addview—动态添加view
一、前言
在日常的开发中经常遇到需要动态添加子view的情况,addview是ViewGroup的特有方法,可以在布局中动态添加view,而view是不存在这个方法的。
二、使用方式
1.方法介绍
addview有以下几种方式
addView(View child) // child 被添加的View
addView(View child, int index) // index 被添加的View的索引
addView(View child, int width, int height) // width,height被添加的View指定的宽高
addView(View view, ViewGroup.LayoutParams params) // params被添加的View指定的布局参数
addView(View child, int index, LayoutParams params)
2.LinearLayout中的使用
首先创建一个xml文件,以ConstraintLayout作为根布局文件,其中包裹一个LinearLayout和两个测试的按钮。
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"android:id="@+id/root_view"><LinearLayoutandroid:id="@+id/container"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><!--一开始就存在的数据--><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="开始存在的数据"android:textColor="#000000"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent" /></LinearLayout><!--测试按钮一--><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="测试一"android:layout_marginBottom="8dp"app:layout_constraintBottom_toBottomOf="parent" /><!--测试按钮二--><Buttonandroid:id="@+id/button2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginEnd="8dp"android:layout_marginRight="8dp"android:text="测试二"android:layout_marginBottom="8dp"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent" />
</android.support.constraint.ConstraintLayout>
一开始的效果如下图
然后编写代码,初始化控件和设置点击事件
public class MainActivity extends AppCompatActivity {private ConstraintLayout layout;private LinearLayout linearLayout;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);layout = findViewById(R.id.root_view);linearLayout = findViewById(R.id.container);findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {addView();}});findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {addviewTwo();}});}/*** 按钮一的点击事件*/private void addView() {TextView textView = new TextView(this);//获取当前时间并格式化String currentTime = dateToStamp(System.currentTimeMillis());textView.setText("测试一..."+currentTime);textView.setTextColor(getResources().getColor(R.color.colorAccent));linearLayout.addView(textView,0);}/*** 按钮二的点击事件*/private void addviewTwo() {TextView textView = new TextView(this);//获取当前时间并格式化String currentTime = dateToStamp(System.currentTimeMillis());textView.setText("测试二..."+currentTime);textView.setTextSize(20f);textView.setTextColor(getResources().getColor(R.color.colorPrimary));linearLayout.addView(textView,1);}/***格式化事件*/public String dateToStamp(long s) {String res;try {SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date = new Date(s);res = simpleDateFormat.format(date);} catch (Exception e) {return "";}return res;}
}
此时我们可以看到我们的按钮使用的是 addview(view,index),这个方法。首先button1的是addView(view,0),button2的是addview(view,1),让我们来看一下效果。
点击两次button1后,如下图:
可以看到新添加的数据都在最上面的第一个。由此我们可以得出,addView(view,0),在LinearLayout中在在顶部添加view。
接下来我们点击几次button2,看看效果
按钮二的index的值是1,根据效果来看addView会一直在第二层中添加view。
总结一下可以知道在LinearLayout中使用addView(view,index),当index=0时,会在顶层添加view,也就是第一层添加。当index=1时,会在第二层添加view。
3.RelativeLayout中使用
我们将布局文件中的LinearLayout变为RelativeLayout
<RelativeLayoutandroid:id="@+id/container"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><!--一开始就存在的数据--><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="开始存在的数据"android:textColor="#000000"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent" />
</RelativeLayout>
当点击按钮时
可以看出来addView(view,index),在RelativeLayout中使用就是添加view层,当index=0是就会在最底层也就是第一层添加view层。当index=1时,就会在第二层添加view层。
三、源码分析
1.addView(view,index)
这里我们会想传index的值是负数会是是怎样的效果呢?,比如index=-1?我们改一下代码,试一下效果
private void addView() {TextView textView = new TextView(this);String currentTime = dateToStamp(System.currentTimeMillis());textView.setText("测试一..."+currentTime);textView.setTextColor(getResources().getColor(R.color.colorAccent));linearLayout.addView(textView,-1);
}
我们修改成上面的代码,运行一下:
ok,我们发现会一直在最下面的一层添加view,为什么会这样,我们点开源码来看一下,其中源码中有一句对index的判断,如下:
if (index < 0) {index = mChildrenCount;}
addInArray(child, index);
源码中如果index<0了,就将index赋值成了布局中子view的个数。有兴趣的可以去看源码。
2.ddView(view) 分析
如果我们在addView中不传参数会怎么样呢?我们继续修改代码运行一下测试
private void addView() {TextView textView = new TextView(this);String currentTime = dateToStamp(System.currentTimeMillis());textView.setText("测试一..."+currentTime);textView.setTextColor(getResources().getColor(R.color.colorAccent));linearLayout.addView(textView);
}
可以发现没有传index的时候,效果和传入index小于0的效果是一样的,这是为什么呢?我们继续点入源码看:
public void addView(View child) {addView(child, -1);
}
看源码发现当没有传index值的时候,会默认index=-1,此时就仍然在最下面添加view。
3.其他的都是比较简单的添加参数,我们这里贴出源码就不细说了
addView(View child, int width, int height)
public void addView(View child, int width, int height) {final LayoutParams params = generateDefaultLayoutParams();params.width = width;params.height = height;addView(child, -1, params);}
addView(View view, ViewGroup.LayoutParams params)
public void addView(View child, LayoutParams params) {addView(child, -1, params);}
四、总结
addView动态添加代码的方法,在LiearLayout中会在竖直或者水平方向添加子view,在RelativeLayout中会增加view的层级数。
Android addview—动态添加view相关推荐
- android 在指定位置添加布局,Android 如何动态添加 View 并显示在指定位置。
引子 最近,在做产品的需求的时候,遇到 PM 要求在某个按钮上添加一个新手引导动画,引导用户去点击.作为 RD,我哗啦啦的就写好相关逻辑了.自测完成后,提测,PM Review 效果. 看完后,PM ...
- android动态添加控件在指定位置,Android 如何动态添加 View 并显示在指定位置。
引子 最近,在做产品的需求的时候,遇到 PM 要求在某个按钮上添加一个新手引导动画,引导用户去点击.作为 RD,我哗啦啦的就写好相关逻辑了.自测完成后,提测,PM Review 效果. 看完后,PM ...
- android viewpager动态加载页面,Android viewpager中动态添加view并实现伪无限循环的方法...
本文实例讲述了Android viewpager中动态添加view并实现伪无限循环的方法.分享给大家供大家参考,具体如下: viewpager的使用,大家都熟悉,它可以实现页面之间左右滑动的切换,这里 ...
- 一种无需留坑为页面动态添加View方案
在Activity或Fragment页面动态添加View,有其应用场景,比如配合运营在首页动态插入H5活动页(如下图手淘的雪花例示[1]),在页面头部插入通知View等.本文结合ActivityLif ...
- databinding通过inflate动态添加view
在MVC中可以通过addView来动态的添加view,那么mvvm通过databinding动态添加view也可以. DataBindingUtil中提供了setContentView和inflate ...
- android radiogroup 添加,如何在android中动态添加textview到radiogroup
大家好, 我们想动态地在radiogroup旁边添加textview.基于服务响应,我们需要在不使用xml的情况下将标签添加到radiogroup. 在某些情况下基于最长无线电如何在android中动 ...
- 在ScrollView中动态添加View
需求:要求在ScrollView中动态添加View,并且添加的View可以进行缩进. 思路:一开始的思路是使用ListView动态添加Item的方法来实现,即当需要新增一个View时,就给适配器新增一 ...
- xcode 学习笔记2:动态添加view
xcode 学习笔记2:动态添加view 2011-07-06 16:48:39| 分类: 计算机学习|字号 订阅 前面说的都是用的Interface Builder来编辑.xib文件来给窗口添加各 ...
- 微信小程序动态添加view
微信小程序动态添加view //index.html<button bindtap='clickMe'> 添加</button> <input type='input' ...
- android ,动态布局 butterknife,与Butterknife绑定在android中动态添加视图
如何绑定布局中存在的视图,该视图使用ButterKnife动态添加到父视图中. 我有一个LinearLayout说容器.我有一个自定义布局,其中包含两个按钮,将此布局称为子视图 在活动中,我将chil ...
最新文章
- LeetCode简单题之用栈操作构建数组
- 个人博客开通--纪念一下。。。
- 关于Activity onNewIntent方法的调用时机
- 解除计算机软件开发协议书,计算机软件著作权转让的协议书
- 前台使用三元运算符判断显示
- quick cocos2d x 手机(Android端)启动过程学习
- 视频编解码学习笔记(一)
- Ubantu16.04安装显卡驱动遇到的坑
- Nacos配置管理-配置热更新
- Spring5各模块之间的依赖关系
- 从你的全世界路过-论演员的自我修养
- 历史上知名的反转现场
- oracle pr,PRMSCAN ORACLE碎片扫描合并工具
- 一代神机落幕!苹果把iPhone 6 Plus列为过时产品,网友吵翻了...
- C++多态虚函数demo
- VMware下Ubuntu与宿主Windows共享文件夹
- 联想笔记本驱动升级,指纹识别不了不成功解决方法
- alter的详细用法
- java毕业生设计在线教育平台计算机源码+系统+mysql+调试部署+lw
- 2021-2027全球与中国巡航型摩托车市场现状及未来发展趋势