来自《第一行代码Android第三版》第227页。
class NewsContentFragment:Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.news_content_frag, container, false)
}
fun refresh(title: String, content: String) {
contentLayout.visibility = View.VISIBLE
newsTitle.text = title
newsContent.text = content
}
}
笔者的版本是不能直接用的,需要val定义一下。
但是在refresh函数中使用val contentLayout : View = 之后,没法findViewById。
询问了ChatGPT,得到以下结果:
class NewsContentFragment : Fragment() {
private lateinit var contentLayout: View
private lateinit var newsTitle: TextView
private lateinit var newsContent: TextView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.news_content_frag, container, false)
contentLayout = view.findViewById(R.id.your_content_layout_id) // 替换成实际的布局 ID
newsTitle = view.findViewById(R.id.newsTitle) // 替换成实际的 TextView ID
newsContent = view.findViewById(R.id.newsContent) // 替换成实际的 TextView ID
return view
}
fun refresh(title: String, content: String) {
contentLayout.visibility = View.VISIBLE
newsTitle.text = title
newsContent.text = content
}
}