Devu Soman
Devu Soman

Reputation: 2266

How to Add/Remove views efficiently?

I have an application which shows a list of items with details. When the user selects the item, the app shows the extra detail. I created two Views which extend RelativeLayout, one for listView and the other for detailed view and added both to the same parent layout. Here is example code for my xml and views.

View with ListView

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
        }

    }

View with details

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));
            }
        });
    }
}

I added these two views to a frame layout. My problem is that when adding/removing the view like this slows the application. How can I add and remove them more efficiently?

Upvotes: 2

Views: 752

Answers (1)

Tobrun
Tobrun

Reputation: 18381

ADDING

This line is not so efficient

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

Why? look at this article

REMOVING

This line is not so efficient

MyView1.this.removeAllViews();

Why? this method will loop al child views and will remove them. If you know which view object you want to remove, you can use removeView(View v) function. This will be more efficient.

Upvotes: 2

Related Questions