Android Studio报错Unresolved reference: photo_title求助
问题解决方法
核心原因
你遇到的「Unresolved reference: photo_title」问题,主要有两个关键原因:
1. 布局代码粘贴错误
你提供的content_photo_details.xml代码完全重复了activity_photo_details.xml的内容,里面根本没有定义photo_title这个TextView,这会导致View Binding无法生成对应的属性。请修正content_photo_details.xml,确保里面包含你创建的photo_title组件,示例如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <TextView android:id="@+id/photo_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:textStyle="bold"/> <!-- 其他图片详情组件,比如ImageView等 --> </LinearLayout>
2. Include布局的访问方式错误
photo_title是在content_photo_details.xml中定义的,而这个布局是被include到activity_photo_details.xml里的。使用View Binding时,不能直接通过binding.photo_title访问,必须先获取include布局对应的Binding对象:
- 默认情况下,include的布局会以「布局文件名转驼峰」的形式作为属性名,比如
content_photo_details.xml对应的属性是contentPhotoDetails - 所以正确的访问方式是:
binding.contentPhotoDetails.photo_title
如果给include标签添加了自定义id(比如android:id="@+id/my_content"),则访问方式变为binding.myContent.photo_title
额外排查步骤
如果按上述修改后仍报错,尝试以下操作:
- 执行Android Studio的「Build → Clean Project」,再「Build → Rebuild Project」,确保Binding类重新生成
- 确认项目的
build.gradle(Module级别)中已启用View Binding:
android { ... buildFeatures { viewBinding true } }
修正后的PhotoDetailsActivity.kt关键代码:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityPhotoDetailsBinding.inflate(layoutInflater) setContentView(binding.root) activateToolbar(true) val photo = intent.getSerializableExtra(PHOTO_TRANSFER) as Photo // 修正后的访问方式 binding.contentPhotoDetails.photo_title.text = photo.title }
内容的提问来源于stack exchange,提问作者Aaryan Goswami
相关产品推荐
相关产品推荐

