Android篇

ROOM数据库使用之ReclerView拖拽排序

2021-03-10  本文已影响0人  w达不溜w
拖拽排序效果图.jpeg
依赖
//Room数据库
implementation 'androidx.room:room-runtime:2.2.5'
kapt 'androidx.room:room-compiler:2.2.5'
//RecyclerView
implementation 'androidx.recyclerview:recyclerview:1.1.0'
//QuickAdapter
implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.41'
Entity

Entity表示一张数据表结构

@Entity
class NavItem {
    //设置主键自增长
    @PrimaryKey(autoGenerate = true)
    var id = 0
    //字段映射具体的数据表字段名,如果没有定义则用属性名,作为列名。
    @ColumnInfo(name = "title")
    var title = ""
    var position = 0
    var type = 0 //0 内容  1 分类

    //必须指定一个构造方法,room框架需要,并且只能指定一个
    //如果有其它构造方法,必须添加@Ignore注解
    constructor()

    @Ignore
    constructor(title: String, position: Int) {
        this.title = title
        this.position = position
    }
    @Ignore
    constructor(title: String, position: Int, type: Int) {
        this.title = title
        this.position = position
        this.type = type
    }
}
DAO

DAO(Database Access Object)代表数据访问对象,所以它是告诉我们的数据库如何操作数据的一种方式.

@Dao
interface CardDao {
    @Query("SELECT * FROM navitem ORDER BY position")
    fun getAllCards():MutableList<NavItem>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(navItem: NavItem)

    @Update
    fun update(navItem: NavItem)

    @Delete
    fun delete(navItem: NavItem)
}
RoomDatabase
@Database(entities = [NavItem::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {

    abstract val cardDao: CardDao

    companion object {

        private val DB_NAME = "jetpack.db"

        @Volatile
        private var instance: AppDatabase? = null

        @Synchronized
        internal fun getInstance(context: Context): AppDatabase? {
            if (instance == null) {
                instance = create(context)
            }
            return instance
        }

        private fun create(context: Context): AppDatabase {
                return Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    DB_NAME
                )
//              .addMigrations(MIGRATION_1_2)//数据库升级
                .allowMainThreadQueries()//允许主线程操作
                .build()
        }

        /**
         * 版本1升级到2的SQL语句
         */
//        private val MIGRATION_1_2: Migration = object : Migration(1, 2) {
//            override fun migrate(database: SupportSQLiteDatabase) {
//                database.execSQL("ALTER TABLE 'navitem' ADD COLUMN 'xxx' INTEGER NOT NULL DEFAULT 0")
//            }
//        }
    }

全局数据共享

object CardDbLiveData {
    val cards: MutableLiveData<List<NavItem>> by lazy { MutableLiveData<List<NavItem>>() }
    val carDao = AppDatabase.getInstance(JetpackApplication.getInstance())!!.cardDao

    fun initCards() {
        carDao.insert(NavItem("已添加", 0, 1))
        carDao.insert(NavItem("数据可视化", 1))
        carDao.insert(NavItem("我的工作台", 2))
        carDao.insert(NavItem("未添加", 3, 1))
        carDao.insert(NavItem("新闻头条", 4))
    }

    fun getCards() = carDao.getAllCards()

    fun update(navItem: NavItem) {
        carDao.update(navItem)
        notifyData()
    }

     fun notifyData() {
        if (isMainThread()) {
            cards.value = getCards()
        } else {
            cards.postValue(getCards())
        }
    }

    private fun isMainThread() = Looper.getMainLooper() == Looper.myLooper()

}
Adapter
class CardsAdapter(datas: List<NavItem>) : BaseItemDraggableAdapter<NavItem, BaseViewHolder>(datas) {


    init {
        val multiTypeDelegate=object: MultiTypeDelegate<NavItem>(){
            override fun getItemType(t: NavItem): Int = t.type
        }
        multiTypeDelegate.registerItemType(0, R.layout.item_cards)
                .registerItemType(1,R.layout.item_cards_cate)
        setMultiTypeDelegate(multiTypeDelegate)
    }
    override fun convert(helper: BaseViewHolder, item: NavItem) {
        helper.setText(R.id.tvTitle,item.title)
    }
}
Activity
class CardManagerActivity : AppCompatActivity() {

    private lateinit var binding: ActivityCardManagerBinding

    private var datas = mutableListOf<NavItem>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_card_manager)
        initData()
    }

    private fun initData() {
        title = "卡片管理"
        initCards()
        //布局方式
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        val divider = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
        //分割线
        val dividerDrawable = ContextCompat.getDrawable(this, R.drawable.custom_divider)
        dividerDrawable?.let { divider.setDrawable(it) }

        binding.recyclerView.addItemDecoration(divider)
        val adapter = CardsAdapter(datas)

        binding.recyclerView.adapter = adapter

        val itemDragAndSwipeCallback = object : ItemDragAndSwipeCallback(adapter) {

            override fun getMovementFlags(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder
            ): Int {
                //限制某些特定item(已添加、未添加)不支持拖拽
                if (viewHolder.itemViewType == 1) {
                    return ItemTouchHelper.Callback.makeMovementFlags(0, 0)
                }
                return super.getMovementFlags(recyclerView, viewHolder)
            }

            override fun onMove(
                recyclerView: RecyclerView,
                source: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                //禁止拖拽到"已添加"上面  "已添加"位置为0
                val to = target.adapterPosition
                if (to == 0) {
                    return false
                }
                return true
            }
        }
        val itemTouchHelper = ItemTouchHelper(itemDragAndSwipeCallback)
        itemTouchHelper.attachToRecyclerView(binding.recyclerView)

        // 开启拖拽
        adapter.enableDragItem(itemTouchHelper, R.id.ivDragSort, false)
        val onItemDragListener = object : OnItemDragListener {
            override fun onItemDragMoving(
                source: RecyclerView.ViewHolder?,
                from: Int,
                target: RecyclerView.ViewHolder?,
                to: Int
            ) {
            }

            override fun onItemDragStart(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
            }

            override fun onItemDragEnd(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
                val newdatas = adapter.data as MutableList<NavItem>
                for ((index, e) in newdatas.withIndex()) {
                    e.position = index
                    CardDbLiveData.update(e)
                }
            }
        }
        adapter.setOnItemDragListener(onItemDragListener)
    }


    private fun initCards() {
        var cards = CardDbLiveData.getCards()
        if (cards.size == 0) {
            //卡片数据库初始化
            CardDbLiveData.initCards()
            cards = CardDbLiveData.getCards()
        }
        datas.addAll(cards)
    }
}
上一篇下一篇

猜你喜欢

热点阅读