关于安卓工作室和按钮在主要活动中不同步的新手问题



这是教程

https://www.youtube.com/watch?time_continue=289&v=OGfZpfn-dGI

在我的安卓工作室中,它无法识别按钮 iv'e 命名它们

android:id="@+id/top_button"android:text="top button"android:text="button 2"android: android:id="@+id/button_2"

top_button.setOnClicklistner { println(top button was clicked)Button_2.setOnClicklistner { println(Button)

我们在这里缺少很多上下文,这些上下文可能会帮助我们为您提供帮助。

不过,首先要做几件事: - XML 布局中的android:id属性是命名相关视图的方式。 这通常是您在代码中引用视图的方式。 -android:text属性是用户在 TextView 等视图上的可见文本。 - 为了使top_button在XML布局文件中引用所需的视图,需要在代码中绑定它。 有几种正常的方法来findViewById()和数据绑定。

我现在假设最后一步是你错过的(在这一点上似乎是最有可能的罪魁祸首(...... 以下是绑定它的几种方法:

方法 1: 使用 Activity 类时

如果要将top_button绑定到Activity类中的视图,则应该可以:

private lateinit var top_button // replace View here with your widget's type
fun onCreate(...) {
super.onCreate(...)
setContentView(R.layout.<i>your_layout_file_name_here</i>)
top_button = findViewById(R.id.top_button)
...
}

方法 2:使用 Fragment 类时

如果要从Fragment类将top_button绑定到视图,则更像这样:

private lateinit var top_button: View // replace View here with your widget's type
fun onCreateView(...): View {
val rootView = layoutInflater.inflate(R.layout.<i>your_layout_file_name_here</i>)
top_button = rootView.findViewById(R.id.top_button)
...
return rootView
}

方法 3:使用数据绑定时

我自己更喜欢这种方法,但你应该谷歌如何在Android中设置数据绑定,因为你需要在build.gradle和所有方面进行更改。

  • 首先,将 XML 布局更改为:
<layout>
<!-- your existing layout XML here -->
</layout>

然后在您的活动/片段中,假设您的 XML 布局文件名为activity_my_cool_screen.xml,您可以执行以下操作:

val binding = ActivityMyCoolScreenBinding.inflate(getLayoutInflater())
binding.topButton.setOnClickListener(...)

请注意,此处的ActivityMyCoolScreenBinding类是自动生成的。 如果它一开始变为红色,则首先验证是否已在项目中准确设置数据绑定,然后如果可以,请确保导入ActivityMyCoolScreenBinding类。 如果更改 XML 布局的文件名,则ActivityMyCoolScreenBinding类名将更改为自动匹配。 但是,如果您确实更改了名称,我建议您使用Android Studio的重构/重命名工具,因为它会搜索您的代码库并在任何地方更新它。 否则,您必须手动完成(可行,但可能乏味且容易出错(。

祝你好运!

最新更新