这是发现上一篇文章的问题之后写的 我们自动创建完之后 产生的控件不会消失 必须手动删除所有有了这篇:
属于 复制
https://blog.csdn.net/Hystudio_lzu/article/details/79212333
1、添加
要在代码中动态添加布局和控件,可以使用ViewGroup类自带的addView方法,如下:
framLayout.addView(animationFrameLayout);
方法接受的参数类型为View,说明可以添加布局和控件,只要继承了View类。需要注意的是,如果你的child没有设置parameters,将会为child设置默认的parameters(引用ViewGroup的),而且不要在draw相关的方法里调用这个方法。
/**
* <p>Adds a child view. If no layout parameters are already set on the child, the
* default parameters for this ViewGroup are set on the child.</p>
*
* <p><strong>Note:</strong> do not invoke this method from
* {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
* {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
*
* @param child the child view to add
*
* @see #generateDefaultLayoutParams()
*/
public void addView(View child) {
addView(child, -1);
}
2、移除
要在代码里移除相应控件,只要调用相应的removeView方法即可。
framLayout.removeView(animationFrameLayout);
与addView方法一样,可以移除继承自View的对象,需要注意的是,不要在draw相关的方法里调用这个方法。
/**
* {@inheritDoc}
*
* <p><strong>Note:</strong> do not invoke this method from
* {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
* {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
*/
@Override
public void removeView(View view) {
if (removeViewInternal(view)) {
requestLayout();
invalidate(true);
}
}
如果你想把所有控件一次性移除,可以调用removeAllView方法
/**
* {@inheritDoc}
*
* <p><strong>Note:</strong> do not invoke this method from
* {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
* {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
*/
@Override
public void removeView(View view) {
if (removeViewInternal(view)) {
requestLayout();
invalidate(true);
}
}