繁体   English   中英

如何从片段中的 xml 获取 EditText 值?

[英]How to get EditText value from xml in fragment?

到目前为止我已经尝试过:

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()将字符串资源作为参数,而不是视图资源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM