我的目標
我正在嘗試使用 viewBinding 訪問在我的片段中創建的小部件。
我做了什么/關于我的應用程式的資訊
我使用的語言是 kotlin。
我已經將以下代碼添加到 gradle 中:
buildFeatures{ dataBinding = true viewBinding = true }
我已經在我的主要活動中測驗了binding.aTextView.setText("Code working.")并且它可以作業。
有什么問題
我已經在活動中測驗了 setText 代碼并且它可以作業。現在的問題是當我進入片段時它不起作用的相同代碼。而且我確信代碼已經執行,因為我在上面放了一個 toast 并且成功執行了 toast,這意味著它至少應該已經達到了那個點,但不確定由于什么原因沒有任何變化。
我的主要活動代碼:
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 顯示“代碼作業”。
uj5u.com熱心網友回復:
我發現您的代碼存在兩個問題。首先,正是邁克爾指出的。當您應該回傳剛剛創建的視圖 (binding.root) 時,您正在回傳超級方法。其次,您當前正在泄漏您的片段。當您查看系結片段時,您應該按照檔案中的onDestroyView()定義將變數設定為 null in 。
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
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/453042.html
標籤:安卓 科特林 安卓片段 android-viewbinding
上一篇:Kotlin不等待協程完成?
