已回答
我有一个 RelativeLayout,当用户垂直或水平滚动时,我会在其中动态添加视图。我推出了自己的 ViewRecycler,因为可能有数千个视图可以组成整个可以滚动的内容,但我在任何时候只显示 30 个左右。想想日历的放大视图。
当我添加即将看到的视图时,我遇到了性能问题,在 RelativeLayout 上调用 onMeasure 级联到 onMeasure 在它的所有子视图上调用。我已经计算出 RelativeLayout 的大小,并且已经在它的 LayoutParameters 上设置了它,因此不需要测量 ViewGroup,也不需要重新测量已经添加的 Views 的最终大小和新的添加的视图与这些视图无关。
演示该问题的简单示例是将视图添加/删除到 RelativeLayout 并观察 onMeasure 被调用,尽管它不会影响 RelativeLayout 的大小或其他视图的位置。
主要的.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/shell"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</LinearLayout>
我的活动.java
public class MyActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewGroup shell = (ViewGroup) findViewById(R.id.shell);
final RelativeLayout container = new RelativeLayout(this) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.d("MyActvity", "onMeasure called on map");
}
};
container.setBackgroundColor(Color.rgb(255, 0, 0));
ViewGroup.LayoutParams containerParams = new ViewGroup.LayoutParams(300, 300);
final TextView childView = new TextView(this);
childView.setBackgroundColor(Color.rgb(0, 255, 0));
childView.setText("Child View");
Button viewToggle = (Button) findViewById(R.id.button);
viewToggle.setText("Add/Remove Child View");
viewToggle.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (childView.getParent() == null) {
container.addView(childView, 400, 30);
} else {
container.removeView(childView);
}
}
});
shell.addView(container, containerParams);
}
}
运行此程序,您将看到对 onMeasure 的 2 次初始(预期)调用,然后每次通过单击按钮添加/删除视图时调用一次。这显然运行良好,但是您可以看到在嵌套视图的复杂布局时不断调用 onMeasure 可能会出现问题。
有没有推荐的方法来绕过这些 onMeasure 调用或至少 onMeasure 调用 measureChildren?