1、添加
要在代码中动态添加布局和控件,可以使用ViewGroup类自带的addView方法,如下:
framLayout.addView(animationFrameLayout);
方法接受的参数类型为View,说明可以添加布局和控件,只要继承了View类。需要注意的是,如果你的child没有设置parameters,将会为child设置默认的parameters(引用ViewGroup的),而且不要在draw相关的方法里调用这个方法。
/**
* 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.
*
* Note: 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.
*
* @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}
*
* Note: 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.
*/
@Override
public void removeView(View view) {
if (removeViewInternal(view)) {
requestLayout();
invalidate(true);
}
}
如果你想把所有控件一次性移除,可以调用removeAllView方法
/**
* {@inheritDoc}
*
* Note: 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.
*/
@Override
public void removeView(View view) {
if (removeViewInternal(view)) {
requestLayout();
invalidate(true);
}
}