Tuesday, February 27, 2018

android kotlin - ViewPager example

MainActivity.kt

package com.cfsuman.kotlinexamples

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

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

        // Initialize a list of string values
        val alphabets = listOf("a","b","c","d","e","f")

        // Initialize a new pager adapter instance with list
        val adapter = AlphabetPagerAdapter(alphabets)

        // Finally, data bind the view pager widget with pager adapter
        view_pager.adapter = adapter
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#edf9ee"
    android:orientation="vertical"
    >
    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</LinearLayout>
page_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linear_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <TextView
        android:id="@+id/tv_lower"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="200sp"
        android:textStyle="bold|italic"
        android:gravity="center"
        android:fontFamily="sans-serif"
        />
    <TextView
        android:id="@+id/tv_upper"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="200sp"
        android:textStyle="bold|italic"
        android:gravity="center"
        android:fontFamily="sans-serif"
        />
    <TextView
        android:id="@+id/tv_footer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="end|bottom"
        android:textStyle="italic"
        android:textSize="20sp"
        android:layout_marginEnd="16dp"
        />
</LinearLayout>
AlphabetPagerAdapter.kt

package com.cfsuman.kotlinexamples

import android.graphics.Color
import android.widget.TextView
import android.view.ViewGroup
import android.support.v4.view.PagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import java.util.*


class AlphabetPagerAdapter(private val list: List<String>) : PagerAdapter() {

    override fun isViewFromObject(v: View, `object`: Any): Boolean {
        // Return the current view
        return v === `object` as View
    }


    override fun getCount(): Int {
        // Count the items and return it
        return list.size
    }


    override fun instantiateItem(parent: ViewGroup?, position: Int): Any {
        // Get the view from pager page layout
        val view = LayoutInflater.from(parent?.context)
                .inflate(R.layout.page_layout,parent,false)

        // Get the widgets reference from layout
        val linearLayout:LinearLayout = view.findViewById(R.id.linear_layout)
        val tvLower: TextView = view.findViewById(R.id.tv_lower)
        val tvLUpper: TextView = view.findViewById(R.id.tv_upper)
        val tvFooter: TextView = view.findViewById(R.id.tv_footer)

        // Set the text views text
        tvLower.text = list.get(position)
        tvLUpper.text = list.get(position).toUpperCase()
        tvFooter.text = "Page ${position+1} of ${list.size}"

        // Set the text views text color
        tvLower.setTextColor(randomLightColor(70,80))
        tvLUpper.setTextColor(randomLightColor(90,70))

        // Set the layout background color
        linearLayout.setBackgroundColor(randomLightColor(10))

        // Add the view to the parent
        parent?.addView(view)

        // Return the view
        return view
    }


    override fun destroyItem(parent: ViewGroup, position: Int, `object`: Any) {
        // Remove the view from view group specified position
        parent.removeView(`object` as View)
    }



    // Generate random light hsv color
    private fun randomLightColor(lightPercent:Int,blackPercent:Int=100):Int{
        // Color variance - red, green, blue etc
        val hue = Random().nextInt(361).toFloat()

        // Color light to dark - 0 light 100 dark
        val saturation = lightPercent.toFloat()/100F

        // Color black to bright - 0 black 100 bright
        val brightness:Float = blackPercent.toFloat()/100F

        // Transparency level, full opaque
        val alpha = 255

        // Return the color
        return Color.HSVToColor(alpha,floatArrayOf(hue,saturation,brightness))
    }
}