'How can i use Multiple layout with same ID's in a Single fragment using ViewBinding in Android

The below code to return the any layout based on the condition check,and Both layout's are same id's , Then how to handle the Textview setText() or Button onClick() scenario in this layout Using ViewBinding.

For example, Suppose we used the any Textview setText(" ") in that inflated layout, Then how can i get which layout object name(binding or binding1) are should be set the value of the Textview.

Code:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
    View view;

    FirstLayoutBinding binding = FirstLayoutBinding.inflate(inflater,container,false);
    SecondLayoutBinding binding1 = SecondLayoutBinding.inflate(inflater,container,false);
    
    if (isTrue){
        view = binding.getRoot();
    }else  {
        view = binding1.getRoot();
    }
  
    return view;
}


Solution 1:[1]

Okay let's assume based on your condition check fragment will inflate the SecondLayoutBindinglayout.

Now you have two different TextViews in layouts.

In second_layout.xml you have TextView with android:id attribute value second_text

In first_layout.xml you have TextView with android:id attribute value first_text

Once fragment completes inflating in onCreateView() with condition. Let's set the text value to the inflated layout's TextView only.

So now we inflated with binding SecondLayoutBinding and we should setText() inside that layout with id second_text in onViewCreated().

onViewCreated()

if (!isTrue) {
    binding1.secondText.setText("MySecondValue");
} else {
    binding.firstText.setText("MyFirstValue");
}

One thing you again need to do is, you have check again which view's id you are trying to call to set it's value. If first_layout get's inflated you cannot set value for views or TextView inside second_layout and vice-versa.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rajasekhar