Search code examples
androidandroid-linearlayoutandroid-viewonbackpressed

Change the visibility of dynamically created Layouts in onBackPressed


I need one help , I have dynamically created Linear Layout , i have to change the visibility of the Created Linear Layout.

My Effort show far :

for (int i=0;i<qty;i++) {
            final View view1 = LayoutInflater.from(BookingDetails.this).inflate(R.layout.dynamic_truck_item, null);
            view_visible.add(false);
            final LinearLayout view_dd=(LinearLayout)view1.findViewById(R.id.view_dd);
}

Back Press:

@Override
    public void onBackPressed() {
        if (backPressedToExitOnce) {
            super.onBackPressed();

        } else {
            this.backPressedToExitOnce = true;

            // Here i have to set the visibility of created linear layout to VIEW.GONE

        }

    }

Solution

  • Create an ArrayList to hold all the references to the LienarLayouts

    private ArrayList<View> collectionOfViews = new ArrayList();
    

    When inflating your layout add the views to the List:

    for (int i=0;i<qty;i++) {
            final View view1 = LayoutInflater.from(BookingDetails.this).inflate(R.layout.dynamic_truck_item, null);
            view_visible.add(false);
            final LinearLayout view_dd=(LinearLayout)view1.findViewById(R.id.view_dd);
            collectionOfViews.add(view_dd);
    }
    

    Then in onBackPressed set the visibility using:

    for(View view : collectionOfViews) {
        view.setVisibility(View.GONE);
    }