问题是所有属于第一个视图组的片段都被添加到了帧布局中
我尝试使用findViewById在每个视图组中查找framelayout,并在添加片段时查找framelayout.getId,但不起作用
活动:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val viewContainer = findViewById<LinearLayoutCompat>(R.id.container)
val file1 = FileView(this)
file1.initView("No.1")
viewContainer.addView(file1)
val file2 = FileView(this)
file2.initView("No.2")
viewContainer.addView(file2)
}
ViewGroup:
class FileView(context: Context) : LinearLayoutCompat(context) {
init {
LayoutInflater.from(context).inflate(R.layout.custom_view, this, true)
}
fun initView(text: String) {
val fragment = TestFragment.newInstance(text)
val manager = (context as FragmentActivity).supportFragmentManager
manager.beginTransaction().add(R.id.file_frameLayout, fragment).commit()
}
}
片段:
class TestFragment : Fragment() {
companion object {
fun newInstance(title: String): TestFragment {
val bundle = Bundle()
bundle.putString("TITLE", title)
return TestFragment().apply {
arguments = bundle
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.test_fragment, container, false)
val title = arguments?.getString("TITLE") as String
view.findViewById<TextView>(R.id.tvTitle).text = title
return view
}
}