Slider using ViewPager - Android Studio - Kotlin

Create slider containing TextView & ImageView using ViewPager and Single Fragment.
>>Watch For Java

Video:


Step 1: Create a new Project or open new project

Step 2: Code

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
        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/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="@dimen/appbar_padding_top"
            android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                app:title="@string/app_name"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:layout_weight="1"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay"
                app:layout_scrollFlags="scroll|enterAlways">

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

fragment_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/constraintLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="20dp"
        tools:context=".MainActivity$PlaceholderFragment">

    <!-- title will set to this TextView, and change on
         slide right/left-->
    <TextView
            android:id="@+id/title_tv"
            android:text="Title"
            android:textAlignment="center"
            android:textSize="25sp"
            android:textColor="#000"
            android:textStyle="bold"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    <!-- image will set to this ImageView, and change on
         slide right/left-->
    <ImageView
            android:id="@+id/image_iv"
            android:background="@color/colorPrimary"
            android:layout_width="match_parent"
            android:layout_height="200dp"/>

    <!-- description will set to this TextView, and change on
         slide right/left-->
    <TextView
            android:id="@+id/description_tv"
            android:text="Here can be long and multiple lined description of the title..."
            android:textSize="20sp"
            android:textColor="#000"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

</LinearLayout>

MainActivity.java

package com.blogspot.atifsoftwares.slider_viewpager_fragment

import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_main.*
import kotlinx.android.synthetic.main.fragment_main.view.*

class MainActivity : AppCompatActivity() {

    /**
     * The [android.support.v4.view.PagerAdapter] that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * [android.support.v4.app.FragmentStatePagerAdapter].
     */
    private var mSectionsPagerAdapter: SectionsPagerAdapter? = null

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


        setSupportActionBar(toolbar)

        //set toolbar title
        toolbar.title = "Slider"
        //set toolbar subtitle
        toolbar.subtitle = "Slide left/right to change..."

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)

        // Set up the ViewPager with the sections adapter.
        container.adapter = mSectionsPagerAdapter

    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        val id = item.itemId

        if (id == R.id.action_settings) {
            return true
        }

        return super.onOptionsItemSelected(item)
    }


    /**
     * A [FragmentPagerAdapter] that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {

        override fun getItem(position: Int): Fragment {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1)
        }

        override fun getCount(): Int {
            // Show 5 total pages.(we will use 5 pages so change it to 5)
            return 5
        }
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    class PlaceholderFragment : Fragment() {

        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            val rootView = inflater.inflate(R.layout.fragment_main, container, false)
            /*since our views are in fragment_main.xml which is inflated in rootView
              so we have to write rootView.oursomeview
              otherwise it will try to find the view in activity_main.xml so app will crash*/
            //handle swipe/slide
            if (arguments!!.getInt(ARG_SECTION_NUMBER) == 1){
                //set title to title_tv
                rootView.title_tv.text = "Title One"
                //set image to image_iv
                rootView.image_iv.setImageResource(R.drawable.battery)
                //set description to description_tv
                rootView.description_tv.text = "The long description of the Title One"
            }
            if (arguments!!.getInt(ARG_SECTION_NUMBER) == 2){
                //set title to title_tv
                rootView.title_tv.text = "Title Two"
                //set image to image_iv
                rootView.image_iv.setImageResource(R.drawable.cpu)
                //set description to description_tv
                rootView.description_tv.text = "The long description of the Title Two"
            }
            if (arguments!!.getInt(ARG_SECTION_NUMBER) == 3){
                //set title to title_tv
                rootView.title_tv.text = "Title Three"
                //set image to image_iv
                rootView.image_iv.setImageResource(R.drawable.devid)
                //set description to description_tv
                rootView.description_tv.text = "The long description of the Title Three"
            }
            if (arguments!!.getInt(ARG_SECTION_NUMBER) == 4){
                //set title to title_tv
                rootView.title_tv.text = "Title Four"
                //set image to image_iv
                rootView.image_iv.setImageResource(R.drawable.display)
                //set description to description_tv
                rootView.description_tv.text = "The long description of the Title Four"
            }
            if (arguments!!.getInt(ARG_SECTION_NUMBER) == 5){
                //set title to title_tv
                rootView.title_tv.text = "Title Five"
                //set image to image_iv
                rootView.image_iv.setImageResource(R.drawable.memory)
                //set description to description_tv
                rootView.description_tv.text = "The long description of the Title Five"
            }
            return rootView
        }

        companion object {
            /**
             * The fragment argument representing the section number for this
             * fragment.
             */
            private val ARG_SECTION_NUMBER = "section_number"

            /**
             * Returns a new instance of this fragment for the given section
             * number.
             */
            fun newInstance(sectionNumber: Int): PlaceholderFragment {
                val fragment = PlaceholderFragment()
                val args = Bundle()
                args.putInt(ARG_SECTION_NUMBER, sectionNumber)
                fragment.arguments = args
                return fragment
            }
        }
    }
}

Step 3: Run Project

Output:
Slider using ViewPager - Android Studio - Kotlin

Comments

Popular posts from this blog

Manage External Storage Permission | Android Studio | Kotlin

Manage External Storage Permission | Android Studio | Java

Add a Back Button to Action Bar Android Studio (Kotlin)