android - 如何从片段中的xml获取EditText值?
问题描述
到目前为止我已经尝试过:
getString(R.id.editBrand) => 这返回 false (R.id.editBrand 返回一个长数字)
view.findViewById(R.id.editBrand) => 运行到 nullreference
任何帮助将不胜感激,谢谢!
我的整个片段:
class CreateFragment : Fragment() {
@SuppressLint("ResourceType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val binding = DataBindingUtil.inflate<FragmentCreateBinding>(inflater,
R.layout.fragment_create,container,false)
val application = requireNotNull(this.activity).application
val dataSource = CarDatabase.getInstance(application).carDatabaseDao
val viewModelFactory = CarViewModelFactory(dataSource, application)
val carViewmodel =
ViewModelProvider(
this, viewModelFactory).get(CarViewmodel::class.java)
val adapter = CarAdapter()
binding.submitButton.setOnClickListener { view : View ->
view.findNavController().navigate(R.id.action_createFragment_to_readFragment)
carViewmodel.onCreated(12, view.findViewById<EditText>(R.id.editBrand).editBrand.toString(), "blue")
}
binding.setLifecycleOwner(this)
return binding.root
}
}
解决方案
采用
binding.editBrand.text.toString()
因为binding
是对您的布局的参考。
如果您使用view.findViewById<EditText>
,view
指的是submitButton
并在其上调用 findViewById 将查找子视图。
getString()
将字符串资源作为参数而不是视图资源。
推荐阅读
- sed - sed 与 find 返回一个字符 11:未终止的 `s' 命令
- javascript - 服务器端的 Onclick 事件 html 按钮
- teamcity - 如何在 TeamCity 2019.1.2 中启用 nuget 提要“FeedService.svc”?
- c# - 如何在 Angular5 Ag-Grid 导出中添加自定义徽标/.jpg 文件到 Header 中的 excel
- pandas - 如何在python中通过pandas中的列名和行名获取值
- pandas - Tensorflow 2“尝试将值(63)转换为不支持的类型(
) 到张量" - html - AngularJS:引导程序中的响应高度
- ios - 在 iOS 13 模拟器上从源代码编译金属着色器会导致 PCH 错误
- python - 从列值中高效地解析和组织信息
- python - 如何让用户选择一个文件将被存储的位置?