【问题标题】:How to Add/Remove views efficiently?如何有效地添加/删除视图?
【发布时间】:2013-01-23 10:53:01
【问题描述】:

我有一个应用程序,它显示带有详细信息的项目列表。当用户选择项目时,应用程序会显示额外的详细信息。我创建了两个扩展RelativeLayout 的视图,一个用于listView,另一个用于详细视图,并将两者添加到相同的父布局中。这是我的 xml 和视图的示例代码。

使用列表视图查看

class MyView1 extends RelativeLayout {

        private Context context = null;

        public MyView1 (Context context) {
            super(context);
            this.context = context;
            createView();
        }

        private void createView() {

            LayoutInflater layoutInflater = (LayoutInflater) context
                    .getSystemService(Service.LAYOUT_INFLATER_SERVICE);
            View view = layoutInflater.inflate(R.layout.layout1, null);
            this.addView(view );
            listview = (ListView) findViewById(R.id.listView);
            listview.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                Object obj  = list.get(position);
                MyView1.this.removeAllViews();
                MyView1.this.addView(new MyView2(context));
            }
        });
         //Set Adapter
        }

    }

查看详情

class MyView2 extends RelativeLayout {

    private Context context = null;

    public MyView2(Context context) {
        super(context);
        this.context = context;
        createView();
    }


    private void createView() {

        LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Service.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.layout2s, null);
        this.addView(view );

        backbutton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                MyView2 .this.removeAllViews();
                MyView2 .this.addView(new MyView1(context));
            }
        });
    }
}

我将这两个视图添加到框架布局中。我的问题是,当像这样添加/删除视图时会减慢应用程序的速度。如何更有效地添加和删除它们?

【问题讨论】:

    标签: android view add removechild


    【解决方案1】:

    添加

    这条线效率不高

    View view = layoutInflater.inflate(R.layout.layout1, null);
    

    为什么?看看这个article

    正在删除

    这条线效率不高

    MyView1.this.removeAllViews();
    

    为什么?此方法将循环所有子视图并将其删除。如果您知道要删除哪个视图对象,可以使用 removeView(View v) 函数。这样会更有效率。

    【讨论】:

    • 没关系。它不会加速应用程序。
    • 其他建议是在 creatView() 方法之前膨胀视图,例如在 onCreate 中。就时间而言,inflating 是一项非常昂贵的功能
    猜你喜欢
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 2020-07-30
    相关资源
    最近更新 更多