Android View Binding问题:编译器自动生成的FoodItemBinding类与文件名不一致且无法修改
Let’s sort out this annoying View Binding issue you’re facing—where the auto-generated FoodItemBinding.java file has a public class name that doesn’t match its filename, and you can’t edit that auto-generated code to fix it directly. Total headache, I know.
Common Causes & Step-by-Step Solutions:
Double-check your layout filename’s naming convention
View Binding generates class names by converting your layout filename to PascalCase. For example,food_item.xmlbecomesFoodItemBinding. If your layout file has inconsistent capitalization (likeFood_Item.xmlorFOODitem.xml), the generator might mangle the class-to-filename mapping. Make sure your layout file is named in all lowercase with underscores, then proceed to rebuild your project.Clean and rebuild your project to clear corrupted cache
Build cache glitches are a frequent culprit here. Do this:- In Android Studio, go to Build > Clean Project
- Then run Build > Rebuild Project
This wipes out old, faulty generated files and creates fresh ones based on your current, correct layout files.
Check for duplicate or mismatched layout files across resource variants
If you have layout files with the same base name in different resource folders (likelayout-land,layout-sw600dp, or debug/release variants), ensure all of them follow the exact same lowercase-with-underscores naming rule. A single mismatched filename in one variant can throw off the binding generator for the whole class.Validate your View Binding setup in build.gradle
Make sure View Binding is enabled properly in your module-levelbuild.gradlefile:android { ... buildFeatures { viewBinding true } }A misconfiguration here can sometimes lead to unexpected generation quirks.
Invalidate Android Studio caches as a last resort
If none of the above works, try resetting the IDE caches:- Go to File > Invalidate Caches...
- Check the box for "Clear file system cache and local history"
- Click Invalidate and Restart
For reference, here’s the error you’re seeing:
class FoodItemBinding is public, should be declared in a file named FoodItemBinding.java
public final class FoodItemBinding implements ViewBinding {
^
This error directly flags a mismatch between the generated class name and the file it’s stored in. The steps above should resolve the root cause in almost all cases.
内容的提问来源于stack exchange,提问作者vikram




