kotlin瀑布流demo

最近学习kotlin,这里用图片展示练习一下

具体怎么配置Android studio的Kotlin环境可以看我的另一篇文章Android Studio使用Kotlin开发

布局的话我这里直接使用RecyclerView



    

MainActivity代码

class MainActivity : AppCompatActivity() {
    private var recyclerView: RecyclerView? = null
    private val spanCount = 1 //每行列数为1
    private val spanCountMore = 3 //每行列数为3
    private val spanSize = 8 //每列之间的间距
    private var layoutManager: StaggeredGridLayoutManager? = null
    private var adapter: RecyleAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
        initGui()
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.navigation, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (layoutManager != null) { //点击菜单时切换列数,3列切换成一列显示大图,再点重新3列瀑布流
            val isOneColumn = layoutManager!!.spanCount == spanCount
            layoutManager!!.spanCount = if (isOneColumn) spanCountMore else spanCount
            adapter!!.setSpanCount(if (isOneColumn) spanCountMore else spanCount) //设置列数
            adapter!!.notifyItemRangeChanged(0, adapter!!.itemCount)
            layoutManager!!.invalidateSpanAssignments()
            val resId = if (!isOneColumn) R.drawable.ic_dashboard_black_24dp else R.drawable.ic_format_line_spacing_black_24dp
            item.icon = resources.getDrawable(resId, null)
        }
        return super.onOptionsItemSelected(item)
    }

    private fun initGui() {
        recyclerView = findViewById(R.id.recyclerView)
        recyclerView!!.setHasFixedSize(true) //避免RecyclerView重新计算大小
        adapter = RecyleAdapter(this, spanCountMore, spanSize)
        layoutManager = StaggeredGridLayoutManager(spanCountMore, StaggeredGridLayoutManager.VERTICAL)
        layoutManager!!.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE //避免滑动加载时跳动
        recyclerView!!.addItemDecoration(SpaceItemDecoration(spanSize)) //设置间距
        recyclerView!!.layoutManager = layoutManager
        recyclerView!!.adapter = adapter
        recyclerView!!.itemAnimator = DefaultItemAnimator() //设置默认加载新Item动画
    }

    inner class SpaceItemDecoration(private val space: Int) : RecyclerView.ItemDecoration() { //切换之后重新设置间距
        override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
            outRect.left = space
            outRect.right = space
            outRect.top = space
            outRect.bottom = space
        }
    }
}

Adapter代码

class RecyleAdapter(private val context: Context, private var spanCount: Int, private val spanSize: Int) : RecyclerView.Adapter() {
    private val imgList = ArrayList() //图片地址列表

    private//        float density = dm.density;
    //        int height = dm.heightPixels;
    val screenWidth: Int //屏幕宽度
        get() {
            val resources = context.resources
            val dm = resources.displayMetrics
            return dm.widthPixels
        }

    init { //初始化图片,重复加载多次显示更多图片
        for (i in 0..5)
            initData(context)
    }

    fun setSpanCount(spanCount: Int) { //设置列数
        this.spanCount = spanCount
    }

    private fun initData(context: Context) {
        for (i in 1..19) { //加载图片资源地址
            imgList.add(context.resources.getIdentifier("pic$i", "drawable", context.packageName))
        }
    }

    override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): MyViewHolder { //初始化Item布局
        val inflate = LayoutInflater.from(context).inflate(R.layout.activity_main, viewGroup, false)
        return MyViewHolder(inflate)
    }

    fun getImageWidthHeight(resId: Int): Float { //初始化图片宽高
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        val bitmap = BitmapFactory.decodeResource(context.resources, resId, options) // 此时返回的bitmap为null
        val outWidth = options.outWidth.toFloat()
        val outHeight = options.outHeight.toFloat()
        return outHeight / outWidth
    }

    override fun onBindViewHolder(viewHolder: RecyleAdapter.MyViewHolder, i: Int) {
        val resourceId = imgList[i]
        val imageLayoutParams = viewHolder.imageView.layoutParams
        imageLayoutParams.width = screenWidth / spanCount - spanCount * spanSize//获取实际展示的图片宽度
        val imageWidthHeight = getImageWidthHeight(resourceId)
        imageLayoutParams.height = (imageLayoutParams.width * imageWidthHeight).toInt()//获取最终图片高度
        viewHolder.imageView.layoutParams = imageLayoutParams//应用高度到布局中
        Glide.with(context).load(resourceId).into(viewHolder.imageView) //使用Glide加载图片
        viewHolder.constraintLayout.setOnClickListener(object : View.OnClickListener {
            private var isDelete = true
            override fun onClick(v: View) { //点击图片删除当前点击的图片
                if (isDelete) {
                    isDelete = false
                    imgList.removeAt(i)
                    notifyItemRemoved(i)
                    notifyItemRangeChanged(i, imgList.size)
                    Thread(Runnable {
                        try {
                            Thread.sleep(300)
                            isDelete = true
                        } catch (e: InterruptedException) {
                            e.printStackTrace()
                        }
                    }).start()
                }
            }
        })
    }

    override fun getItemCount(): Int {
        return imgList.size
    }

    inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var constraintLayout: CardView
        val imageView: ImageView

        init {
            constraintLayout = itemView.findViewById(R.id.constrainLayout)
            imageView = itemView.findViewById(R.id.tv_hello)
        }
    }
}

图片使用CardView显示,这样有圆角和阴影显示效果会更好看



   


展示效果

TIM图片20190306133311.gif

Github Demo地址

你可能感兴趣的:(kotlin瀑布流demo)