viewBinding 未在片段内进行任何更改

viewBinding not making any changes inside fragment

我的目标

我正在尝试使用 viewBinding 访问在我的片段中创建的小部件。

我做了什么/关于我的应用程序的信息

有什么问题

我已经测试了 activity 中的 setText 代码并且它有效。现在的问题是相同的代码,当我进入片段时它不起作用。我确信代码已经执行,因为我在它上面放了一个祝酒词并且祝酒词成功执行,这意味着它应该至少已经达到了那个点但不确定由于什么原因没有任何变化。

我的主要活动代码:

class MainProgramActivity : AppCompatActivity() {
lateinit var binding: ActivityMainProgramBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainProgramBinding.inflate(layoutInflater)
    setContentView(binding.root)
    replaceFragment(FragmentMainPage())
}
private fun replaceFragment(fragment: Fragment){
    val fragmentManager = supportFragmentManager
    val fragmentTransaction = fragmentManager.beginTransaction()
    fragmentTransaction.replace(R.id.fragmentContainerView,fragment)
    fragmentTransaction.commit()
}

}

我的片段代码:

class FragmentMainPage : Fragment(R.layout.fragment_main_page) {

lateinit var binding: FragmentMainPageBinding

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    Toast.makeText(getActivity(),"Text!",Toast.LENGTH_SHORT).show();
    binding = FragmentMainPageBinding.inflate(layoutInflater)
    binding.aTextView.setText("Code working") //<-- I want this code to make changes towards the textView
    return super.onCreateView(inflater, container, savedInstanceState)
}

}

aTextView 本身在开始时是空的,预期结果将是 aTextView 显示“代码正在运行”。

我发现您的代码有两个问题。首先,正是迈克尔指出的内容。当您应该返回刚创建的视图 (binding.root) 时,您返回了 super 方法。其次,您目前正在泄漏您的片段。当您查看片段时,您应该根据 the documentation.

中的定义将 onDestroyView() 中的变量设置为 null
class FragmentMainPage : Fragment(R.layout.fragment_main_page) {

  private var _binding: FragmentMainPageBinding? = null
  private val binding get() = _binding!! // non-null variable in order to avoid having safe calls everywhere

  // create the view through binding
  override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
  ): View? {
    _binding = FragmentMainPageBinding.inflate(layoutInflater, container, false)
    return binding.root
  }

  // view already created, do whatever with it
  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    binding.aTextView.setText("Code working")
  }

  // clear the binding in order to avoid memory leaks
  override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
  }
}