我可以在运行时填充一个ViewStub。假设我想让它消失,然后根据发生的某些事件(例如,根据用户在屏幕上选择的内容膨胀和缩小的工具栏)再次填充它。
我可以使用View.setVisibility(View.GONE)....是否还有其他方法?
或者我在这里做错了什么吗?
谢谢!:)
布局膨胀可能会很昂贵,特别是在旧设备上。将ViewStub视为一种惰性加载机制,用于可能或可能不会扩展的视图子树,而不是在运行时交换视图层次结构中的部分的方法。一旦充气,使用VISIBLE/GONE之间进行交换没有任何问题。GONE会使框架在昂贵的遍历期间跳过该子树。
只要您不需要充气视图使用的内存,这就是正确的。将可见性设置为GONE不会释放任何内存;它仅将视图标记为已隐藏,以供布局和绘制目的。要释放viewstub充气视图的内存,您必须实际删除充气视图,并再次替换为新的viewstub以供将来使用。
是的,你可以随时删除。我刚刚做过了。
ViewStub stub = findById(...);
View v = stub.inflate();
并在任何事件上设置视图可见性。
v.setVisibility(View.GONE);
private Boolean isErrorViewInflated = false;
private ViewStub errorViewStub;
/* here a method that gets a view. If the view is already inflated,
* it uses that view, else it inflates the view. It also creates a viewStub
* object which will be used to replace the inflated view when it needs to
* be deflated.
/
public RelativeLayout getErrorView() {
RelativeLayout errorView = null;
if (isErrorViewInflated) {
errorView = activity.findViewById(R.id.error_view);
} else {
ViewStub stub = activity.findViewById(R.id.error_view_stub);
errorView = (RelativeLayout) stub.inflate();
errorViewStub = new ViewStub(getContext(), stub.getLayoutResource());
isErrorViewInflated = true;
}
return errorView;
}
/* Here's the code that deflates an inflated ErrorView back to a ViewStub
*/
private void deflateErrorView() {
if (isErrorViewInflated) {
RelativeLayout errorView = activity.findViewById(R.id.error_view);
ViewGroup parent = (ViewGroup)errorView.getParent();
int index = parent.indexOfChild(errorView);
parent.removeView(errorView);
parent.addView(errorViewStub, index);
isErrorViewInflated = false;
}
}
setVisibility(View.GONE)
更加具有描述性。 - st0le