如何计算布局中的视图数量

How to count amount of views in layout

Android Studio 是否有办法显示 XML 布局中存在的视图数量?众所周知,布局应包含 <=80 个视图,因此超过此数量就会出现此警告,因此告知数量将非常有帮助。

LayoutName.xml has more than 80 views, bad for performance

public class FragmentApple extends android.support.v4.app.Fragment {

    public FragmentApple () {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_apple,container,false);

        int num = FragmentApple.getChildCount(); Log.d("Number of views in layout: ", "" + num);

        return v;
    }
}

你试过了吗?:

layout.getChildCount();

更新

根据我们在评论中的讨论,您应该在代码中执行以下操作:

public class FragmentApple extends android.support.v4.app.Fragment {

public FragmentApple () {
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_apple,container,false);



    return v;
}

@Override
public void onStart(){
super.onStart()
RelativeLayout (or Linear as in your xml) rl = (RelativeLayout) v.findViewbyId(R.id.your_layout_id)

int num = rl.getChildCount();
 Log.d("Number of views in layout: ", "" + num);
}

    }

对于这个问题的新手,您可以使用 android 工作室的 android 设备监视器中的视图层次结构:

从您的设备或模拟器打开应用程序,然后浏览到您要检查的视图

1- 从 Studio 的菜单栏打开

 tools -> Android -> Android device monitor

2- 来自Android 设备监控菜单栏打开

 window -> open perspective -> Hierarchy view

它可能会加载一段时间。

如果您想了解更多:https://developer.android.com/studio/profile/hierarchy-viewer.html