How to remove first view pager item in kotlin?

那年仲夏 提交于 2021-01-29 05:29:55

问题


I use View-Pager2 in my application that Which displays several same fragments. I also have a dialog fragment and inside it, I manage view pager items(add and remove items). Every fragment inside the view-pager has an id that saved in the SQLite database.

So, My problem is, When I remove the first item of view-pager, It does not delete and still remains but another item removed and when I launch the app again, I see the first item has been removed and everything is ok.

Main Activity Class:

class MainActivity : AppCompatActivity() {

private lateinit var databaseHelper: DatabaseHelper
private lateinit var myPagerAdapter: MyPagerAdapter

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    databaseHelper = DatabaseHelper(this)
    myPagerAdapter = MyPagerAdapter(supportFragmentManager, lifecycle)
    view_pager.adapter = myPagerAdapter

    if (databaseHelper.getCount().toInt() == 0) {
        //red
        databaseHelper.insertData(0, Color.argb(255, 244, 67, 54))
        //blue
        databaseHelper.insertData(1, Color.argb(255, 33, 150, 243))
        //green
        databaseHelper.insertData(2, Color.argb(255, 76, 175, 80))
    }

    btn_show.setOnClickListener {
        val ft = supportFragmentManager.beginTransaction()
        ft.add(FragmentTwo(), "Dialog")
        ft.addToBackStack(null)
        ft.commit()
    }

}

private inner class MyPagerAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) :
    FragmentStateAdapter(fragmentManager, lifecycle) {

    override fun getItemCount(): Int {
        return databaseHelper.getCount().toInt()
    }

    override fun createFragment(position: Int): Fragment {
        return FragmentOne.newInstance(position)
    }

}

fun setViewPagerPosition(position: Int) {
    view_pager.currentItem = position
}

fun setViewPagerChanged() {
    myPagerAdapter.notifyDataSetChanged()
}
}

FragmentOne class:

class FragmentOne : Fragment() {

companion object {
    fun newInstance(position: Int): FragmentOne {
        val fragment = FragmentOne()
        val bundle = Bundle()
        bundle.putInt("id", position)
        fragment.arguments = bundle
        return fragment
    }
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    return inflater.inflate(R.layout.fragment_one, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val databaseHelper = DatabaseHelper(context)
    val id = arguments?.getInt("id")
    frame_frag1?.setBackgroundColor(databaseHelper.getColor(id))
}

}

FragmentTwo class (dialog fragment):

class FragmentTwo : DialogFragment() {

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_dialog, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val databaseHelper = DatabaseHelper(context)
    btn_remove?.setOnClickListener {
        (context as MainActivity).setViewPagerPosition(2)
        databaseHelper.deleteData("0")
        databaseHelper.updateRowsRemoveTab(id)
        (context as MainActivity).setViewPagerChanged()
    }
}

}

And its DatabaseHelper class:

class DatabaseHelper(context: Context?) : SQLiteOpenHelper(context, "tabs.db", null, 1) {

private val TBL_NAME: String = "tabs"

override fun onCreate(db: SQLiteDatabase?) {
    db?.execSQL("CREATE TABLE $TBL_NAME (ID INTEGER , COLOR INTEGER)")
}

override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
    db?.execSQL("DROP TABLE IF EXISTS $TBL_NAME")
    onCreate(db)
}

fun insertData(id: Int, color: Int) {
    val db = this.writableDatabase
    val cv = ContentValues()
    cv.put("ID", id)
    cv.put("COLOR", color)
    db.insert(TBL_NAME, null, cv)
}

fun getColor(id: Int?): Int {
    val db = this.readableDatabase
    var color = 0
    val cursor = db.rawQuery("select COLOR from $TBL_NAME where ID = $id", null)
    if (cursor.moveToFirst())
        do {
            color = (cursor.getInt(0))
        } while (cursor.moveToNext())
    return color
}

fun updateRowsRemoveTab(id: Int) {
    val db = this.writableDatabase
    db.execSQL("update tabs set ID = ID-1 where ID > $id")
}

fun deleteData(id: String) {
    val db = this.writableDatabase
    db.delete(TBL_NAME, "ID = ?", arrayOf(id)).toLong()
}

fun getCount(): Long {
    val db = this.readableDatabase
    val count = DatabaseUtils.queryNumEntries(db, TBL_NAME)
    db.close()
    return count
}

}

Can you help me?


回答1:


I do your do without viewpager2 and it ok. I copy your codes and just edit your view pager adapter to this:

    private inner class MyPagerAdapter(fragmentManager: FragmentManager) :
    FragmentPagerAdapter(fragmentManager) {

    override fun getItem(position: Int): Fragment {
        return FragmentOne.newInstance(position)
    }

    override fun getCount(): Int {
        return databaseHelper.getCount().toInt()
    }

    override fun getItemPosition(`object`: Any): Int {
        return PagerAdapter.POSITION_NONE
    }
}

Dont forget to add PagerAdapter.POSITION_NONE to getItemPosition method.

This way is correct but I don't know how to do this with viewpager2.



来源:https://stackoverflow.com/questions/63035179/how-to-remove-first-view-pager-item-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!