【发布时间】:2016-08-25 01:51:30
【问题描述】:
在我的情况下,我想实现自定义ViewGroup,从FrameLayout 派生,但我希望所有从xml 添加的子视图不直接添加到此视图中,而是添加到此自定义ViewGroup 中包含的FrameLayout 中。
让我举例说明一下。
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/frame_layout_child_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<FrameLayout
android:id="@+id/frame_layout_top"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</merge>
我想将所有子视图重定向到FrameLayout,ID 为frame_layout_child_container。
所以我当然会像这样覆盖addView() 方法
@Override
public void addView(View child) {
this.mFrameLayoutChildViewsContainer.addView(child);
}
但这肯定不行,因为这次mFrameLayoutChildViewsContainer 没有添加到根自定义视图中。
我的想法是始终在此容器的顶部保留一些视图 frame_layout_top 并且添加到自定义组件中的所有子视图都应该转到 frame_layout_child_container
使用自定义视图的示例
<CustomFrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
</CustomFrameLayout>
所以在这种情况下TextView 应该添加到frame_layout_child_container
是否可以像我描述的那样将所有视图委托给子 ViewGroup。
我还有其他想法,例如每次添加视图时使用 bringToFront() 方法以使它们保持正确的 z 轴顺序,或者例如在添加视图时,将其保存到数组中,然后在扩展自定义视图后将所有视图添加到此孩子FrameLayout
建议在这种情况下该怎么做,以免在每次添加新视图时重新膨胀所有布局而影响性能,如果可以以其他方式实现的话。
【问题讨论】:
-
您确定要扩展
FrameLayout吗?orientation属性仅适用于LinearLayout。 -
我根本不需要方向属性 :) 所以我的答案是肯定的
标签: android performance android-layout android-view android-custom-view