0

I have a fragment, and inside that I inflate another layout file. This means there are multiple buttons on the page with the same ID:

<Button android:layout_height="30dp"
        android:layout_width="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        android:text="Delete"
        android:id="@+id/delete_seed" tools:layout_editor_absoluteX="0dp"
        android:textSize="10sp" android:paddingTop="5dp"
        android:paddingRight="5dp"
        android:paddingLeft="5dp"
        android:paddingBottom="5dp"
        android:padding="5dp"/>

So when I call:

Button deletebutton = rootView.findViewById(R.id.delete_seed);
deletebutton.setVisibility(View.GONE);

It only removes the first one. How can I target all the buttons?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Chud37
  • 4,907
  • 13
  • 64
  • 116

3 Answers3

0

You have included a layout inside a fragment. To target that button you need to find the button id with respect to the included layout and not the rootView.

View includedLayout = rootView.findViewById(R.id.include_id);
Button deletebutton = rootView.findViewById(R.id.delete_seed);
deletebutton.setVisibility(View.GONE);

//Find included button
Button includedDeleteButton = includedLayout.findViewById(R.id.delete_seed);
includedDeleteButton.setVisibility(View.GONE);
Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49
  • Okay, but how can I loop through all views on the page? – Chud37 Aug 02 '18 at 12:21
  • You will need to loop through included layout and the root layout. Use the ViewGroup from both rootView and includedLayout to get list of all views from the layout. `ViewGroup vg = rootView.getParent();` – Hemant Parmar Aug 02 '18 at 12:23
0

You could use tag instead of id and loop through everything like explained here : https://stackoverflow.com/a/16262479/1243048

Maelig
  • 2,046
  • 4
  • 24
  • 49
0

Work around : It is not a good practice to do it using id. Better to use tag. But as a work around use the below code

private void hideViews(int id, ViewGroup view) {
    for (int i = 0; i < view.getChildCount(); i++) {
        View v = view.getChildAt(i);
        if (v instanceof Button && v.getId() == id) {
           v.setVisibility(View.GONE)
        } else if (v instanceof ViewGroup) {
            this.loopViews((ViewGroup) v);
        }
    }
} 
Viswanath Kumar Sandu
  • 2,230
  • 2
  • 17
  • 34