我很難處理我的 Android 應用程式中的片段。有些事情看起來很奇怪,其他人的眼神可能會有所啟發。
這是片段的 XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@ id/theFragmentID"
tools:context=".NiceFragment">
<TextView
android:id="@ id/labelOne"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Place_Holder-One" />
<TextView
android:id="@ id/labelTwo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Place_Holder=Two" />
<EditText
android:id="@ id/inpNew"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="60px" />
.....
</FrameLayout>
這是我在應用程式某處的一些 Kotlin 代碼(即在片段的onCreateView()方法中):
val labelOne = fragHandle.findViewById<TextView>(R.id.labelOne)
labelOne.text = "Some interesting sentence"
val labelTwo = fragHandle.findViewById<TextView>(R.id.labelTwo)
labelTwo.text = "Some other very interesting sentence"
最后這是我在上面代碼的最后一行得到的錯誤:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at me.soft.myapp.NiceFragment.onCreateView(NiceFragment.kt:99)
上面的四行 Kotlin 代碼可能更好地定位在片段的onViewCreated()方法中。但我的問題的重點是:
為什么第 4 行有問題,而第 2 行完美運行?
從我的角度來看labelOne和labelTwo只是兩個完全等價的物件。
我也嘗試將這段代碼放在onViewCreated()中,但問題仍然存在。
我可能會遺漏哪些細節?
uj5u.com熱心網友回復:
請檢查在您的 kotlin 類中寫入的匯入的 xml。將匯入錯誤的 XML 檔案。
uj5u.com熱心網友回復:
在使用 kotlin 時,在處理片段時有一個很好的選擇。你也應該考慮這一點。將您的布??局名稱移動到 Fragment 建構式并執行以下代碼。
class AccountFragment : Fragment(R.layout.fragment_account) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val labelOne = view.findViewById<TextView>(R.id.labelOne)
}
}
在片段中使用 onViewCreated 而不是 onCreateView 始終是一個好習慣。
快樂編碼
uj5u.com熱心網友回復:
在我看來,你可以使用viewBinding
在你的gradle中添加這個
viewBinding {
enabled = true
}
并且在您的片段中可以使用這樣的系結
private lateinit var binding: FragmentHomeNavBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentHomeNavBinding.inflate(LayoutInflater.from(requireContext()), container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply {
myTextView.text = "some text"
}
}
viewBinding 替換 findViewById,ViewBinding 具有 null 安全性和型別安全性
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/514037.html
標籤:安卓科特林安卓片段
