在 onBackPressed 中更改动态创建的布局的可见性

Change the visibility of dynamically created Layouts in onBackPressed

我需要一个帮助,我动态创建了线性布局,我必须更改创建的线性布局的可见性。

我的努力显示:

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

返回按:

@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

        }

    }

创建一个 ArrayList 来保存对 LienarLayouts 的所有引用

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

展开布局时将视图添加到列表中:

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

然后在 onBackPressed 中使用以下方法设置可见性:

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

你应该从循环中取出 View view1 然后你应该取出 ViewGroup 在索引处添加视图。

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

之后,在您的 onBackPressed() 方法中,您可以通过索引获取视图并简单地将可见性设置为 gone/visible.

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