多个以编程方式将片段添加到ViewGroup

时间:2019-05-05 04:45:44

标签: fragment viewgroup

  1. 将多个“自定义”视图组添加到“活动”中的线性布局。
  2. 每个自定义视图组都包含一个片段。

问题是所有属于第一个视图组的片段都被添加到了帧布局中

我尝试使用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
    }

}

enter image description here

0 个答案:

没有答案