我正在尝试为DialogFragment
中的不同选项卡显示不同的内容,但是由于某种原因,无论选择了哪个选项卡,内容文本都会重复显示第一项。选项卡名称按预期方式正确显示。我认为问题出在DialogFragment
的{{1}}循环内的for
类中,但是我不知道该领域需要改变什么。
我可以用什么代替createInstance
中的id
?
myListDescriptions[id]
预期结果
当前结果
物品类
for (item in myListTitles) {
adapter.addFragment(id, FragmentDialogContent.createInstance(myListDescriptions[id]))
}
适配器类
data class Item (val myDialogTitle: String,
val myDialogDescription: String)
DialogFragment类
class MyDialogAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
private var mTitleCollection: MutableList<String> = ArrayList()
private var mFragmentCollection: MutableList<Fragment> = ArrayList()
fun addFragment(title: String, fragment: Fragment) {
mTitleCollection.add(title)
mFragmentCollection.add(fragment)
}
override fun getPageTitle(position: Int): CharSequence? {
return mTitleCollection[position]
}
override fun getItem(position: Int): Fragment {
return mFragmentCollection[position]
}
override fun getCount(): Int {
return mFragmentCollection.size
}
}
片段类
class FragmentDialogContent(val myList: ArrayList<Item>) : DialogFragment() {
private var mText = ""
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return customView
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val b = AlertDialog.Builder(activity)
.setTitle("Dialog Title")
.setPositiveButton(getString(android.R.string.ok)) { dialog, _ -> dialog.dismiss() }
val adapter = MyDialogAdapter(childFragmentManager)
for (item in myListTitles) {
adapter.addFragment(id, FragmentDialogContent.createInstance(myListDescriptions[id]))
}
b.setView(customView)
return b.create()
}
companion object {
fun createInstance(txt: String): FragmentDialogContent {
val fragment = FragmentDialogContent()
fragment.mText = txt
return fragment
}
}
}
以前使用的代码
答案 0 :(得分:-1)
无法在此处进行测试(我现在正在工作),但是过去我遇到过类似的问题,因此我通过将其添加到片段分页器适配器中来解决了这个问题:
override fun getItemPosition(`object`: Any): Int {
return POSITION_NONE
}
编辑:kotlin版本
答案 1 :(得分:-1)
您必须进行一些更改。
// Returns the fragment to display for that page
when (position) {
0 // tab # 0 - This will show FirstFragment
-> return addFragment("title 1", MyDialog.createInstance(mTitleCollection[position]))
1 // Tab #1 - This will show SecondFragment
-> return addFragment("title2", MyDialog.createInstance(mTitleCollection[position]))
2 // Tab # 2 - This will show ThirdFragment
-> return addFragment("title 3", MyDialog.createInstance(mTitleCollection[position]))
else -> return null
}
为避免混淆,我会处理适配器中的所有逻辑,将fragmentManager和列表传递给构造函数,然后可以在类内部本地访问它们。
MyDialogAdapter(fm,mList1,MList2)