Android开发:XML设置Button ID后findViewById提示未找到ID错误
解决findViewById找不到btnrotation的问题
XML文件中已设置Button的ID为btnrotation,但在Java代码中调用findViewById(R.id.btnrotation)时出现错误,错误提示翻译为:未找到id为'btnrotation'的声明
XML布局代码
<androidx.appcompat.widget.AppCompatButton android:id="@+id/btnrotation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/rorationbtn" android:layout_below="@+id/imgbox" android:layout_centerInParent="true" android:layout_marginTop="50dp"> </androidx.appcompat.widget.AppCompatButton>
Java代码
public class rotation extends AppCompatActivity { AppCompatButton rotate; ImageView imgbox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rotation); getSupportActionBar().setTitle("Rotation"); imgbox=findViewById(R.id.imgbox); rotate=findViewById(R.id.btnrotation); } }
解决步骤
- 确认布局文件对应:检查上述Button代码是否存在于
activity_rotation.xml中,Java代码里setContentView(R.layout.activity_rotation)指定的布局必须包含这个Button。 - 清理重建项目:点击Android Studio菜单栏的
Build->Clean Project,完成后再点击Rebuild Project,强制更新R文件。 - 检查ID一致性:确保XML中的
btnrotation和Java中调用的R.id.btnrotation拼写、大小写完全一致(当前代码拼写没问题,可跳过此步)。 - 检查布局嵌套:如果Button嵌套在
ScrollView、ViewPager等容器内,确认没有因布局层级导致的查找问题,直接调用findViewById会遍历整个布局树,只要Button在当前布局内就可以找到。
内容的提问来源于stack exchange,提问作者Sumita Das
相关产品推荐
相关产品推荐

