这可能是一个非常愚蠢的问题,但我创建了这样的结构,但我确实遇到了性能问题。
public class OuterClass extends LinearLayout {
private LinearLayout viewPort;
public OuterClass(Context context) {
super(context);
initComponents(context);
addInnerClass();
}
private void initComponents(Context context){
LayoutInflater inflater = (LayoutInflater) getContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.view_port, this);
viewPort = (LinearLayout) findViewById(R.id.view_port);
}
private void addInnerClass(){
for ( int i = 0; i < k; i++ ){
InnerClass functio = this.new InnerClass();
viewPort.addView(functio);
}
}
private class InnerClass extends RelativeLayout{
private LineraLayout newLines;
public InnerClass() {
super(OuterClass.this.context);
initComponents(OuterClass.this.context);
addNLines();
}
private void initComponents(Context context){
LayoutInflater inflater = (LayoutInflater) getContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.job_function_container, this);
newLines = (LinearLayout) findViewById(R.id.newLines);
}
private void addInnerOfInner(View view){
newLines.addView(view);
}
private void addNLines(){
for ( int i = 0; i < k1; i++ ){
InnerOfInnerClass line = this.new InnerOfInnerClass();
addInnerOfInner(line);
}
}
public class InnerOfInnerClass extends RelativeLayout{
private InnerOfInnerClass(){
super(OuterClass.this.context);
initComponents(OuterClass.this.context);
}
private void initComponents(Context context){
LayoutInflater inflater = (LayoutInflater) getContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.new_line, this);
// Setting some fields.
}
}
}
更具体地说,如果我尝试在每个 InnerClass 中创建 5 个 InnerClass 对象和 5 个 InnerOfInner Class 对象,那真的很慢。如果有人能向我解释原因,我将不胜感激。谢谢。
最佳答案
从您的代码中似乎没有任何东西可以作为巨大的危险信号脱颖而出。至于为什么它在创建部分真的很慢可能有多种原因。需要考虑的事项:
如何从 Activity 中实例化 OuterClass?它只被调用一次还是您正在创建多个实例。你拥有的越多,速度就越慢。
R.layout.new_line、R.layout.job_function_container、R.layout.view_port 上还有多少其他小部件?只有一个小部件与每个小部件 50 个可能会导致一些明显的延迟。
您使用什么设备进行测试?在旧的 Droid 上运行比在 Nexus 7 上测试要慢得多。如果您使用的是模拟器......好吧,总是期望一切都运行缓慢。
最后(可能也是最相关的),我认为最大的减速是嵌套布局的复杂性或深度。正如 Ancantus 提到的,尽量避免深布局层。走得太深,奇怪的事情可能会开始发生。主要是由于此类层次结构消耗的内存量。
如果您需要一种添加 View 的动态方式,我建议您查看 ListView、GridView,或者如果您的目标平台允许,甚至是 GridLayout。在我的脑海中,我想不出为什么你需要这么复杂的设计。尽管存在特殊情况需求,但通常总有更简单、更正确的方法。
这里有一些关于布局优化的有用链接,可能对您有帮助,也可能没有帮助:
关于java - Android 布局的内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13013589/