Change the visibility of dynamically created Layouts in onBackPressed

442 views Asked by At

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

        }

    }
2

There are 2 answers

2
Ognian Gloushkov On BEST ANSWER

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);
}
1
bharat7777 On

your should take out View view1 from loop and after that you should take ViewGroup for adding view at index.

((ViewGroup)view1.findViewById(R.id.background)).addView(child, index);

after that at your onBackPressed() method you can get view by index and simply set visibility to gone/visible.

@Override
public void onBackPressed() { 
   ((ViewGroup)view1.findViewById(R.id.background)).getChildAt(index).setVisibility(View.GONE);
}