'How to use tools:context to associtate Fragment files?

Recently I came across the use-case of using tools:context in my layout files for activities. I learned that I can use it to associate an Activity class file to my layout file.

But how can I use it to associate a Fragment class file to any layout?

Bacuase as I have tried, it is only showing Activity list in autocomplete suggestion.



Solution 1:[1]

There is a bug in Android Studio, you have to write it manually, it will appear red(indicating it's unresolved) until you finish typing, then it will appear in green

Solution 2:[2]

Create a fragment with a layout file and see the layout file for tools:context.

Solution 3:[3]

Key point: Autocomplete is not showing name, manually enter it and it will compile.

Solution 4:[4]

I just had the same problem and typing in the fragment name didn't get the fragment name recognized in the tools:context=".NameFragment" statement.

What did work was first deleting both the class and xml files for that fragment and then:

  1. Right click on the package name and choose New->Fragment->Fragment (Blank)
  2. Enter in your fragment name (the layout name is automatically created on the same form) and click Finish.

This method created both the class and xml files at the same time. and at this point, the tools:context statement in my xml file had my fragment name automatically and was not red but green text (indicating that it was recognized). I'm seeing this on Android Studio Bumblebee 2021.1.1.

Earlier I had created the xml file first and then created the class file (and had problems with the fragment class file name not being recognized by the tools:context statement).

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 Mohammad Elsayed
Solution 2 double-beep
Solution 3 Shimon Rothschild
Solution 4 Jim