首页 > 解决方案 > 如何从片段中的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
    }
}

标签: androidkotlin

解决方案


采用

binding.editBrand.text.toString()

因为binding是对您的布局的参考。

如果您使用view.findViewById<EditText>,view指的是submitButton并在其上调用 findViewById 将查找子视图。

getString()将字符串资源作为参数而不是视图资源。


推荐阅读