Deepshikha Puri, the young Indian Entrepreneur heading the mobile development trade from years to successive extent, has worked with numerous clients and many tremendous brands in this industry of mobile encompassing in India and overseas maintaining promising work relationships with each of them with an impression to manage it's whole thing.

Friday, November 10, 2017

Video Demo:




In Marshmallow (Api level 23 or higher), Google had changed the way of asking permissions. If we want to access the camera, gallery etc of the marshmallow user, then we have to asked these permission during runtime otherwise over app should crash. There are two type of permission Normal Permission and Dangerous Permission

NORMAL PERMISSION- Normal permission in marshmallow is directly granted while installation of application. Examples of normal permission is given below:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>

DANGEROUS PERMISSION- Dangerous Permissions which provide access the personal data of user such as gallery, location, camera etc. Examples of dangerous permission is given below:

<uses-permission android:name="android.permission.READ_CALENDAR"/>
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_SMS"/>

In this tutorial I will cover the runtime permission in Marshmallow in android kotlin. DOWNLOAD SOURCE CODE FROM BELOW.


kotlin request permission

Add this dependency in your gradle:
compile 'io.vrinda.kotlinpermissions:kotlinpermissions:1.1'

AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="deepshikha.com.runtimepermission">
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CALL_PHONE"/>
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#ffffff"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="2">


        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal"
                android:weightSum="2">

                <RelativeLayout
                    android:id="@+id/rl_camera"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1">

                    <ImageView
                        android:layout_width="100dp"
                        android:id="@+id/iv_camera"
                        android:layout_marginTop="50dp"
                        android:layout_height="100dp"
                        android:layout_centerHorizontal="true"
                        android:src="@drawable/camera" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_marginTop="5dp"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/iv_camera"
                        android:layout_centerHorizontal="true"
                        android:text="Take Picture"
                        android:textColor="#000000"
                        android:textSize="18dp"
                        android:textStyle="bold"/>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:layout_alignParentBottom="true"
                        android:background="#CDCDCD"></View>
                </RelativeLayout>


                <RelativeLayout
                    android:id="@+id/rl_gallery"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1">

                    <ImageView
                        android:layout_width="100dp"
                        android:id="@+id/iv_gallery"
                        android:layout_marginTop="50dp"
                        android:layout_height="100dp"
                        android:layout_centerHorizontal="true"
                        android:src="@drawable/gallery" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_marginTop="5dp"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/iv_gallery"
                        android:layout_centerHorizontal="true"
                        android:text="Gallery Picture"
                        android:textColor="#000000"
                        android:textSize="18dp"
                        android:textStyle="bold"/>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:layout_alignParentBottom="true"
                        android:background="#CDCDCD"> </View>
                </RelativeLayout>


            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_alignParentBottom="true"
                android:background="#EAEAEA"></View>


            <View
                android:layout_width="1dp"
                android:layout_height="match_parent"
                android:layout_centerHorizontal="true"
                android:background="#EAEAEA">&lt/View>


        </RelativeLayout>


        <!---->


        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal"
                android:weightSum="2">

                <RelativeLayout
                    android:id="@+id/rl_call"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1">

                    <ImageView
                        android:layout_width="100dp"
                        android:id="@+id/iv_call"
                        android:layout_marginTop="50dp"
                        android:layout_height="100dp"
                        android:layout_centerHorizontal="true"
                        android:src="@drawable/call" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_marginTop="5dp"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/iv_call"
                        android:layout_centerHorizontal="true"
                        android:text="Call"
                        android:textColor="#000000"
                        android:textSize="18dp"
                        android:textStyle="bold"/>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:layout_alignParentBottom="true"
                        android:background="#CDCDCD"></View>
                </RelativeLayout>


                <RelativeLayout
                    android:id="@+id/rl_contacts"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1">

                    <ImageView
                        android:layout_width="100dp"
                        android:id="@+id/iv_contact"
                        android:layout_marginTop="50dp"
                        android:layout_height="100dp"
                        android:layout_centerHorizontal="true"
                        android:src="@drawable/contactlist" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_marginTop="5dp"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/iv_contact"
                        android:layout_centerHorizontal="true"
                        android:text="Contact"
                        android:textColor="#000000"
                        android:textSize="18dp"
                        android:textStyle="bold"/>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:layout_alignParentBottom="true"
                        android:background="#CDCDCD"></View>
                </RelativeLayout>


            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_alignParentBottom="true"
                android:background="#EAEAEA"></View>


            <View
                android:layout_width="1dp"
                android:layout_height="match_parent"
                android:layout_centerHorizontal="true"
                android:background="#EAEAEA"></View>


        </RelativeLayout>


    </LinearLayout>


</RelativeLayout>
MainActivity.kt:
package deepshikha.com.runtimepermission

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import android.provider.MediaStore
import android.util.Log
import io.vrinda.kotlinpermissions.PermissionCallBack
import io.vrinda.kotlinpermissions.PermissionsActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : PermissionsActivity() {
    var CAMERAMODE:Int=1
    var GALLERYMODE:Int=2
    var CALLMODE:Int=3
    var CONATACTMODE:Int=4
    var boolean_camera:Boolean=false
    var boolean_gallery:Boolean=false
    var boolean_call:Boolean=false
    var boolean_contact:Boolean=false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        rl_camera.setOnClickListener {
            if (boolean_camera) {
                takePhoto()
            }else {
                fn_permission(Manifest.permission.CAMERA,CAMERAMODE)
            }
        }

        rl_gallery.setOnClickListener {
            if (boolean_gallery) {
                takegallerypicture()
            }else {
                fn_permission(Manifest.permission.READ_EXTERNAL_STORAGE,GALLERYMODE)
            }
        }

        rl_call.setOnClickListener {
            if (boolean_call) {
                phonecall()
            }else {
                fn_permission(Manifest.permission.CALL_PHONE,CALLMODE)
            }
        }


        rl_contacts.setOnClickListener {
            if (boolean_contact){
                readcontact()

            }else{
                fn_permission(Manifest.permission.READ_CONTACTS,CONATACTMODE)

            }

        }

    }

    fun fn_permission(permission:String,mode:Int){
        requestPermissions(permission, object : PermissionCallBack {
            override fun permissionGranted() {
                super.permissionGranted()
                Log.v("Call permissions", "Granted")

                if (mode==CAMERAMODE){
                    takePhoto()
                    boolean_camera=true
                }else if (mode==GALLERYMODE){
                    takegallerypicture()
                    boolean_gallery=true
                }else if (mode==CALLMODE){
                    phonecall()
                    boolean_call=true
                }else if (mode==CONATACTMODE){
                    readcontact()
                    boolean_contact=true
                }

            }

            override fun permissionDenied() {
                super.permissionDenied()
                Log.v("Call permissions", "Denied")

                if (mode==CAMERAMODE){
                    boolean_camera=false
                }else if (mode==GALLERYMODE){
                    boolean_camera=false
                }else if (mode==CALLMODE){
                    boolean_call=false
                }else if (mode==CONATACTMODE){
                    boolean_contact=false
                }

            }
        })
    }

    fun takePhoto() {
        val intent1 = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (intent1.resolveActivity(packageManager) != null) {
            startActivityForResult(intent1, CAMERAMODE)
        }
    }

    fun takegallerypicture() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"
        if (intent.resolveActivity(packageManager) != null) {
            startActivityForResult(intent, GALLERYMODE)
        }
    }


    @SuppressLint("MissingPermission")
    fun phonecall() {
        val intent = Intent(Intent.ACTION_CALL);
        intent.data = Uri.parse("tel:1234567890s")
        startActivity(intent)
    }


    fun readcontact(){
        val intent = Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI)
        startActivity(intent)
    }
}


Saturday, October 14, 2017

Video Demo:



As we know that Viewpager is used to slide the screen. There are alots of tutorial of using viewpager in android programmatically with java, But there are limited example of using viewpager with kotlin. So here I am showing tutorial of using Viewpager in android using kotlin. Download source code from here.

android kotlin viewpager example

activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_margin="20dp"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"></android.support.v4.view.ViewPager>
</RelativeLayout>


MainActivity.kt:
package com.deepshikha.viewpagerkotlin

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

class MainActivity : AppCompatActivity() {

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

        val obj_adapter : ViewPagerAdapter
        obj_adapter = ViewPagerAdapter(supportFragmentManager)
        viewpager.adapter=obj_adapter
    }
}

Model.kt:
package com.deepshikha.viewpagerkotlin

/**
 * Created by deepshikha on 11/9/17.
 */
public class Model{
    var str_name=""
    var str_des=""
    var str_color=""
    var int_image=0

    constructor(str_name: String, int_image: Int,str_color:String,str_des:String) {
        this.str_name = str_name
        this.int_image = int_image
        this.str_color=str_color
        this.str_des=str_des
    }
}
fragment_category.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#91ecbd"
    android:id="@+id/ll_main"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center"
        android:text=""
        android:textColor="#000000"
        android:textSize="20dp"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/iv_image"
        android:scaleType="centerCrop"
        android:layout_width="match_parent"
        android:layout_height="250dp" />

    <TextView
        android:id="@+id/tv_des"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center"
        android:text=""
        android:textColor="#000000"
        android:textSize="15dp"
        android:textStyle="italic" />

</LinearLayout>
CategoryFragment.kt:
package com.deepshikha.viewpagerkotlin

import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView

/**
 * Created by deepshikha on 12/9/17.
 */
public class CategoryFragment : Fragment() {
    val al_category = ArrayList()
    var int_position: Int = 0
    lateinit var iv_image12: ImageView
    lateinit var tv_des: TextView
    lateinit var tv_name: TextView
    lateinit var ll_main: LinearLayout
    lateinit var view12: View

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
         view12 = inflater!!.inflate(R.layout.fragment_category, container, false)


        fn_arraylist()
        init()

        return view12
    }

    public fun init() {

        iv_image12 = view12?.findViewById(R.id.iv_image) as ImageView
        tv_name = view12?.findViewById(R.id.tv_name) as TextView
        tv_des = view12?.findViewById(R.id.tv_des) as TextView
        ll_main = view12?.findViewById(R.id.ll_main) as LinearLayout

        int_position = arguments.getInt("position")
        iv_image12.setImageResource(al_category.get(int_position).int_image)
        tv_name.setText(al_category.get(int_position).str_name)
        tv_des.setText(al_category.get(int_position).str_des)
        ll_main.setBackgroundColor(Color.parseColor(al_category.get(int_position).str_color))
    }


    public fun fn_arraylist() {
        al_category.add(Model("BURJ KHALIFA", R.drawable.burjkhalifa, "#f9b994","The Burj Khalifa, known as the Burj Dubai before its inauguration, is a megatall skyscraper in Dubai, United Arab Emirates."))
        al_category.add(Model("Taj Mahal", R.drawable.tajmahal, "#bdf3f7","he Taj Mahal is an ivory-white marble mausoleum on the south bank of the Yamuna river in the Indian city of Agra. It was commissioned in 1632 by the Mughal emperor, Shah Jahan, to house the tomb of his favourite wife, Mumtaz Mahal."))
        al_category.add(Model("Sagrada Família", R.drawable.sagrada, "#91ecbd","The Basílica i Temple Expiatori de la Sagrada Família is a large unfinished Roman Catholic church in Barcelona, designed by Catalan architect Antoni Gaudí"))
    }
}



Saturday, September 9, 2017

Video Demo:



As we know that now kotlin is officially supported by Android studio. So here I am creating a demo to show listview in android by using kotlin. Download source code from here.

android kotlin listview example

activity_main.xml:

<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorPrimary"
        android:text="Listview in kotlin"
        android:textSize="20dp"
        android:gravity="center"
        android:textColor="#FFFFFF"
        android:textStyle="bold"/>

    <ListView
        android:layout_width="match_parent"
        android:id="@+id/lv_flower"
        android:layout_height="match_parent"></ListView>

</LinearLayout>

MainActivity.kt:

package com.deepshikha.listviewinkotlin

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

public class MainActivity : AppCompatActivity() {

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

        val al_flower=ArrayList<Model_flower>()
        al_flower.add(Model_flower("Rosa",R.drawable.rosa,"A rose is a woody perennial flowering plant of the genus Rosa, in the family Rosaceae, or the flower it bears. There are over a hundred species and thousands of cultivars"))

        al_flower.add(Model_flower("Lotus",R.drawable.lotus,"Nelumbo nucifera, also known as Indian lotus, sacred lotus, bean of India, Egyptian bean or simply lotus, is one of two extant species of aquatic plant in the family Nelumbonaceae."))

        al_flower.add(Model_flower("Cherry Blossom",R.drawable.nelumbo,"A cherry blossom (or commonly known in Japan as sakura) is the flower of any of several trees of genus Prunus, particularly the Japanese cherry, Prunus serrulata"))

        al_flower.add(Model_flower("Bird of Paradise",R.drawable.birdofparadise,"The birds-of-paradise are members of the family Paradisaeidae of the order Passeriformes. The majority of species are found in eastern Indonesia, Papua New Guinea, and eastern Australia. The family has 42 species in 15 genera"))

        al_flower.add(Model_flower("Tulips",R.drawable.tulips,"The tulip is a Eurasian and North African genus of herbaceous, perennial, bulbous plants in the lily family, with showy flowers. About 75 wild species are accepted"))

        al_flower.add(Model_flower("Dahlia",R.drawable.dahlia,"Dahlia is a genus of bushy, tuberous, herbaceous perennial plants native to Mexico. A member of the Asteraceae, dicotyledonous plants, related species include the sunflower, daisy, chrysanthemum, and zinnia."))

        al_flower.add(Model_flower("Water Lilies",R.drawable.waterlilies,"Lilium is a genus of herbaceous flowering plants growing from bulbs, all with large prominent flowers. Lilies are a group of flowering plants which are important in culture and literature in much of the world."))

        al_flower.add(Model_flower("Gazania",R.drawable.gazania,"Gazania is a genus of flowering plants in the family Asteraceae, native to Southern Africa. They produce large, daisy-like composite flowerheads in brilliant shades of yellow and orange, over a long period in summer."))

        al_flower.add(Model_flower("Orchid",R.drawable.orchid,"The Orchidaceae are a diverse and widespread family of flowering plants, with blooms that are often colourful and fragrant, commonly known as the orchid family. Along with the Asteraceae, they are one of the two largest families of flowering plants"))


        val obj_adapter : CustomAdapter
        obj_adapter = CustomAdapter(applicationContext,al_flower)
        lv_flower.adapter=obj_adapter
    }

}

adapter_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:background="#ffffff"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/iv_flower"
        android:layout_width="150dp"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:textColor="#000000"
            android:textSize="15dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tv_des"
            android:maxLines="5"
            android:ellipsize="end"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:textColor="#000000"
            android:textSize="13dp"/>
    </LinearLayout>


</LinearLayout>

CustomAdapter.kt:

package com.deepshikha.listviewinkotlin

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView

/**
 * Created by deepshikha on 31/7/17.
 */

class CustomAdapter(context: Context,al_flower:ArrayList<Model_flower>) : BaseAdapter(){

    private val mInflator: LayoutInflater
    private val al_flower:ArrayList<Model_flower>

    init {
        this.mInflator = LayoutInflater.from(context)
        this.al_flower=al_flower
    }

    override fun getCount(): Int {
        return al_flower.size
    }

    override fun getItem(position: Int): Any {
        return al_flower.get(position)
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
        val view: View?
        val vh: ListRowHolder
        if (convertView == null) {
            view = this.mInflator.inflate(R.layout.adapter_layout, parent, false)
            vh = ListRowHolder(view)
            view.tag = vh
        } else {
            view = convertView
            vh = view.tag as ListRowHolder
        }

        vh.label.text = al_flower.get(position).str_name
        vh.tv_des.text = al_flower.get(position).str_des
        vh.iv_image.setImageResource(al_flower.get(position).int_image)
        return view
    }
}

private class ListRowHolder(row: View?) {
    public val label: TextView
    public val tv_des: TextView
    public val iv_image: ImageView

    init {
        this.label = row?.findViewById<TextView>(R.id.tv_name) as TextView
        this.tv_des = row?.findViewById<TextView>(R.id.tv_des) as TextView
        this.iv_image = row?.findViewById<ImageView>(R.id.iv_flower) as ImageView
    }


}

Model_flower.kt:

package com.deepshikha.listviewinkotlin

/**
 * Created by deepshikha on 31/7/17.
 */
public class Model_flower{
    var str_name:String =""
    var str_des:String =""
    var int_image:Int=0

    constructor(str_name:String,int_image:Int,str_des:String){
        this.int_image=int_image
        this.str_name=str_name
        this.str_des=str_des

    }

}





Monday, July 31, 2017

Video Demo:



Kotlin is very simple language you can easily learn it if you have a good knowledge of java and android studio. In this tutorial I am creating the list using kotlin classes. You can download the source code from below.


kotlin recyclerview tutorial

activity_main.xml:
<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textColor="#ffffff"
        android:textSize="15dp"
        android:textStyle="bold"
        android:gravity="center"
        android:background="@color/colorPrimary"
        android:text="@string/app_name"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

</LinearLayout>
MainActivity.kt:
package com.deepshikha.recyclerviewkotlin
import android.app.Activity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.Window
import android.view.WindowManager
import android.widget.LinearLayout
import kotlinx.android.synthetic.main.activity_main.*
import net.simplifiedcoding.recyclerviewexample.CustomAdapter

class MainActivity : Activity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)

        setContentView(R.layout.activity_main)

        val users = ArrayList()
        users.add(Model_Details("Kaju katli", "Kaju katli, also known as kaju Katari or kaju barfi, is an Indian dessert similar to a barfi.",R.drawable.kaju))
        users.add(Model_Details("Doughnut", "The doughnut is popular in many countries and prepared in various forms as a sweet snack that can be homemade or purchased in bakeries, supermarkets, food stalls, and franchised specialty outlets",R.drawable.donuts))
        users.add(Model_Details("Panna cotta", "Panna cotta is an Italian dessert of sweetened cream thickened with gelatin and molded. The cream may be aromatized with rum, coffee, vanilla, or other flavorings.",R.drawable.panna_cotta))
        users.add(Model_Details("Rose Cookies", "Rose cooky is a famous South Indian snack made during festivals",R.drawable.rosecookies))
        users.add(Model_Details("Belgian waffle", "In North America, Belgian waffles are a variety of waffle with a lighter batter, larger squares, and deeper pockets than ordinary American waffles",R.drawable.belgianwaffle))

        val obj_adapter = CustomAdapter(users)

        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
        recyclerView.adapter = obj_adapter
    }

}

adapter_details.xml:
<?xml version="1.0" encoding="utf-8"?gt;
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="160dp"
    android:background="#EAEAEA"
    android:layout_centerHorizontal="true"
    android:orientation="horizontal"gt;

    <ImageView
        android:layout_width="155dp"
        android:scaleType="centerCrop"
        android:layout_height="155dp"
        android:id="@+id/iv_name"/gt;


<LinearLayout
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:background="#FFFFFF"
    android:padding="10dp"
    android:layout_marginBottom="5dp"
    android:layout_height="match_parent"gt;
    <TextView
        android:id="@+id/tv_name"
        android:textStyle="bold"
        android:text="adfaldfkjalk"
        android:textSize="15dp"
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" /gt;

    <TextView
        android:id="@+id/tv_des"
        android:layout_marginTop="5dp"
        android:textColor="#000000"
        android:textSize="11dp"
        android:text="adfaldfkjalk "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" /gt;
</LinearLayoutgt;
</LinearLayoutgt;
CustomAdapter.kt:
package net.simplifiedcoding.recyclerviewexample

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.deepshikha.recyclerviewkotlin.Model_Details
import com.deepshikha.recyclerviewkotlin.R
import kotlinx.android.synthetic.main.adapter_details.view.*

class CustomAdapter(val userList: ArrayList) : RecyclerView.Adapter() {

    //this method is returning the view for each item in the list
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.adapter_details, parent, false)
        return ViewHolder(v)
    }

    //this method is binding the data on the list
    override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
        holder.bindItems(userList[position])
    }

    //this method is giving the size of the list
    override fun getItemCount(): Int {
        return userList.size
    }

    //the class is hodling the list view
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bindItems(user: Model_Details) {
            itemView.tv_name.text=user.name
            itemView.tv_des.text=user.des
            itemView.iv_name.setImageResource(user.image)

        }
    }
}
Model_Details.kt:
package com.deepshikha.recyclerviewkotlin

/**
 * Created by deepshikha on 28/7/17.
 */
 data class Model_Details(val name:String,val des:String,val image:Int)


Saturday, July 22, 2017

Video Demo:

In this tutorial I am using expandable listview with default navigation drawer. Download source code from here

android custom navigation drawer with expandablelistview

activity_main.xml:
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/container_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

        </LinearLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:background="#234E6F"
        android:layout_height="60dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:textColor="#ffffff"
            android:layout_centerInParent="true"
            android:textStyle="bold"
            android:id="@+id/tv_name"/>


        <ImageView
            android:layout_width="25dp"
            android:layout_centerVertical="true"
            android:layout_height="30dp"
            android:layout_marginLeft="10dp"
            android:src="@drawable/menu_icon"/>
        <RelativeLayout
            android:layout_width="40dp"
            android:id="@+id/rl_menu"
            android:layout_height="match_parent"></RelativeLayout>

    </RelativeLayout>

        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
</LinearLayout>

    </LinearLayout>
    <LinearLayout
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#FFFFFF">

        <include layout="@layout/menu_layout"></include>

    </LinearLayout>

</android.support.v4.widget.DrawerLayout>
menu_layout.xml:

<?xml version="1.0" encoding="utf-8"?>

<ScrollView android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:orientation="vertical">


    <RelativeLayout
        android:id="@+id/rl_profile"
        android:layout_width="match_parent"
        android:layout_height="150dp">

        <ImageView

            android:id="@+id/iv_image"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_centerVertical="true"
            android:src="@drawable/profile_image" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="20dp"
            android:layout_toRightOf="@+id/iv_image"
            android:text="David"
            android:textColor="#000000"
            android:textSize="15dp" />


    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="#EAEAEA"></View>


    <ExpandableListView
        android:id="@+id/ev_menu"
        android:nestedScrollingEnabled="false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </ExpandableListView>
</LinearLayout>
</ScrollView>
MainActivity.java:
package com.deepshikha.navigationdrawer;

import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList al_main = new ArrayList<>();
    ExpandableListView ev_list;
    CountryAdapter obj_adapter;
    String TAG = "MainActivity";
    private DrawerLayout mDrawerLayout;
    HomeFragment fragment;
    TextView tv_name;
    RelativeLayout rl_menu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fn_data();
        init();

    }

    private void init() {

        getSupportActionBar().hide();
        ev_list = (ExpandableListView) findViewById(R.id.ev_menu);
        tv_name = (TextView) findViewById(R.id.tv_name);
        rl_menu = (RelativeLayout) findViewById(R.id.rl_menu);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        obj_adapter = new CountryAdapter(MainActivity.this, al_main);
        ev_list.setAdapter(obj_adapter);
        ev_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                setListViewHeight(parent, groupPosition);
                return false;
            }
        });

        setExpandableListViewHeightBasedOnChildren(ev_list);

        fragment = new HomeFragment();
        Bundle bundle = new Bundle();
        bundle.putString("name", al_main.get(0).getStr_country());
        bundle.putString("des", al_main.get(0).getAl_state().get(0).getStr_description());
        bundle.putString("dish", al_main.get(0).getAl_state().get(0).getStr_name());
        bundle.putString("image", al_main.get(0).getAl_state().get(0).getStr_image());
        tv_name.setText(al_main.get(0).getStr_country());

        fragment.setArguments(bundle);
        getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, "HomeFragment").addToBackStack("null").commit();


        rl_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDrawerLayout.openDrawer(Gravity.LEFT);
            }
        });
    }

    private void setListViewHeight(ExpandableListView listView, int group) {
        ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter();
        int totalHeight = 0;
        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(),
                View.MeasureSpec.EXACTLY);
        for (int i = 0; i < listAdapter.getGroupCount(); i++) {
            View groupItem = listAdapter.getGroupView(i, false, null, listView);
            groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);

            totalHeight += groupItem.getMeasuredHeight();

            if (((listView.isGroupExpanded(i)) && (i != group))
                    || ((!listView.isGroupExpanded(i)) && (i == group))) {
                for (int j = 0; j < listAdapter.getChildrenCount(i); j++) {
                    View listItem = listAdapter.getChildView(i, j, false, null,
                            listView);
                    listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);

                    totalHeight += listItem.getMeasuredHeight();

                }
            }
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        int height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1));
       /* if (height < 10)
            height = 200;*/
        params.height = height;
        listView.setLayoutParams(params);
        listView.requestLayout();

    }

    private void fn_data() {

        String str_data = loadJSONFromAsset();

        try {
            JSONObject jsonObject_country = new JSONObject(str_data);
            JSONArray jsonArray_country = jsonObject_country.getJSONArray("country");
            al_main = new ArrayList<>();
            for (int i = 0; i < jsonArray_country.length(); i++) {
                Model_country obj_country = new Model_country();
                JSONObject jsonObject = jsonArray_country.getJSONObject(i);
                JSONArray jsonArray_dishes = jsonObject.getJSONArray("dishes");
                ArrayList al_dishes = new ArrayList<>();
                for (int j = 0; j < jsonArray_dishes.length(); j++) {

                    JSONObject jsonObject_dishes = jsonArray_dishes.getJSONObject(j);
                    Model_Dish obj_dish = new Model_Dish();
                    obj_dish.setStr_name(jsonObject_dishes.getString("dishname"));
                    obj_dish.setStr_description(jsonObject_dishes.getString("description"));
                    obj_dish.setStr_image(jsonObject_dishes.getString("image"));
                    al_dishes.add(obj_dish);
                }

                obj_country.setAl_state(al_dishes);
                obj_country.setStr_country(jsonObject.getString("name"));

                al_main.add(obj_country);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    public static void setExpandableListViewHeightBasedOnChildren(ExpandableListView expandableListView) {
        CountryAdapter adapter = (CountryAdapter) expandableListView.getExpandableListAdapter();
        if (adapter == null) {
            return;
        }
        int totalHeight = expandableListView.getPaddingTop() + expandableListView.getPaddingBottom();
        for (int i = 0; i < adapter.getGroupCount(); i++) {
            View groupItem = adapter.getGroupView(i, false, null, expandableListView);
            groupItem.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            totalHeight += groupItem.getMeasuredHeight();

            if (expandableListView.isGroupExpanded(i)) {
                for (int j = 0; j < adapter.getChildrenCount(i); j++) {
                    View listItem = adapter.getChildView(i, j, false, null, expandableListView);
                    listItem.setLayoutParams(new ViewGroup.LayoutParams(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED));
                    listItem.measure(View.MeasureSpec.makeMeasureSpec(0,
                            View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                            .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                    totalHeight += listItem.getMeasuredHeight();

                }
            }
        }

        ViewGroup.LayoutParams params = expandableListView.getLayoutParams();
        int height = totalHeight + expandableListView.getDividerHeight() * (adapter.getGroupCount() - 1);

        if (height < 10)
            height = 100;
        params.height = height;
        expandableListView.setLayoutParams(params);
        expandableListView.requestLayout();
    }

    public String loadJSONFromAsset() {
        String json = null;
        try {

            InputStream is = getAssets().open("dishes.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }

        Log.e(TAG, "Json response " + json);
        return json;

    }

    public void fn_selectedPosition(int group, int child) {

        fragment = new HomeFragment();
        Bundle bundle = new Bundle();
        bundle.putString("name", al_main.get(group).getStr_country());
        bundle.putString("des", al_main.get(group).getAl_state().get(child).getStr_description());
        bundle.putString("dish", al_main.get(group).getAl_state().get(child).getStr_name());
        bundle.putString("image", al_main.get(group).getAl_state().get(child).getStr_image());
        fragment.setArguments(bundle);

        getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, "HomeFragment").addToBackStack("null").commit();
        mDrawerLayout.closeDrawer(Gravity.LEFT);

        tv_name.setText(al_main.get(group).getStr_country());
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}
Model_country.java:
package com.deepshikha.navigationdrawer;

import java.util.ArrayList;

/**
 * Created by deepshikha on 12/7/17.
 */

public class Model_country {
    String str_country;
    ArrayList al_state;
    public Model_country() {
    }

    public Model_country(String str_country, ArrayList al_state) {
        this.str_country = str_country;
        this.al_state = al_state;
    }


    public String getStr_country() {
        return str_country;
    }

    public void setStr_country(String str_country) {
        this.str_country = str_country;
    }

    public ArrayList getAl_state() {
        return al_state;
    }

    public void setAl_state(ArrayList al_state) {
        this.al_state = al_state;
    }
}
Model_Dish.java:
package com.deepshikha.navigationdrawer;

/**
 * Created by deepshikha on 12/7/17.
 */

public class Model_Dish {
    String str_name;
    String str_description;
    String str_image;

    public Model_Dish(String str_name, String str_description, String str_image) {
        this.str_name = str_name;
        this.str_description = str_description;
        this.str_image = str_image;
    }

    public String getStr_image() {
        return str_image;
    }

    public void setStr_image(String str_image) {
        this.str_image = str_image;
    }

    public Model_Dish() {

    }



    public String getStr_name() {
        return str_name;
    }

    public void setStr_name(String str_name) {
        this.str_name = str_name;
    }

    public String getStr_description() {
        return str_description;
    }

    public void setStr_description(String str_description) {
        this.str_description = str_description;
    }
}
fragment_home.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:orientation="vertical">

<RelativeLayout
    android:layout_width="match_parent"
    android:background="#FFFFFF"
    android:layout_height="240dp">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_marginTop="20dp"
        android:scaleType="centerCrop"
        android:id="@+id/iv_image"/>
</RelativeLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Dish Name"
        android:textSize="25dp"
        android:id="@+id/tv_dishname"
        android:gravity="center"
        android:textStyle="bold"
        android:textColor="#000000"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Dish Name"
        android:textSize="18dp"
        android:padding="10dp"
        android:layout_marginTop="5dp"
        android:id="@+id/tv_description"
        android:gravity="left"
        android:textColor="#000000"
        />

</LinearLayout>

HomeFragment.java:
package com.deepshikha.navigationdrawer;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;


public class HomeFragment extends Fragment {

    View view;
    TextView  tv_dishname, tv_description;
    ImageView iv_image;
    String str_name, str_disname, str_des, str_imagename;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        init();
        return view;
    }

    private void init() {

        str_name = getArguments().getString("name");
        str_disname = getArguments().getString("dish");
        str_des = getArguments().getString("des");
        str_imagename = getArguments().getString("image");
//        str_imagename = "chinese";
        tv_dishname = (TextView) view.findViewById(R.id.tv_dishname);
        tv_description = (TextView) view.findViewById(R.id.tv_description);
        iv_image = (ImageView) view.findViewById(R.id.iv_image);


        tv_dishname.setText(str_disname);
        tv_description.setText(str_des);

        int resourceImage = getActivity().getResources().getIdentifier(str_imagename, "drawable", getActivity().getPackageName());
        iv_image.setImageResource(resourceImage);


    }


}
adapter_childview.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="20dp"
    android:paddingLeft="50dp"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:textSize="15dp"
        android:gravity="center_vertical"
        android:textColor="#000000"
        android:id="@+id/tv_name"/>



</LinearLayout>
adapter_header.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textSize="15dp"
        android:paddingLeft="10dp"
        android:gravity="center_vertical"
        android:textColor="#ffffff"
        android:background="#234E6F"
        android:id="@+id/tv_name"/>

</LinearLayout>

CountryAdapter.java:
package com.deepshikha.navigationdrawer;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by deepshikha on 12/7/17.
 */

public class CountryAdapter extends BaseExpandableListAdapter {
    Context context;
    ArrayList al_country;

    public CountryAdapter(Context context, ArrayList al_country) {
        this.context = context;
        this.al_country = al_country;
    }

    @Override
    public int getGroupCount() {
        return al_country.size();
    }

    @Override
    public int getChildrenCount(int i) {
        return al_country.get(i).getAl_state().size();
    }

    @Override
    public Object getGroup(int i) {
        return al_country.get(i);
    }

    @Override
    public Object getChild(int i, int i1) {
        return al_country.get(i).getAl_state().get(i1);
    }

    @Override
    public long getGroupId(int i) {
        return i;
    }

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
        if (view==null){

            LayoutInflater layoutInflater = (LayoutInflater) this.context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.adapter_header, null);
        }
        TextView tv_state = (TextView)view.findViewById(R.id.tv_name);
        tv_state.setText(al_country.get(i).getStr_country());
        return view;
    }

    @Override
    public View getChildView(final int i, final int i1, boolean b, View view, ViewGroup viewGroup) {
        if (view==null){

            LayoutInflater layoutInflater = (LayoutInflater) this.context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.adapter_childview, null);
        }

        TextView tv_state = (TextView)view.findViewById(R.id.tv_name);

        tv_state.setText(al_country.get(i).getAl_state().get(i1).getStr_name());
        tv_state.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((MainActivity)context).fn_selectedPosition(i,i1);
            }
        });
        return view;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return false;
    }


}

Monday, July 17, 2017

Video Demo:



You can easily view your online pdf file from url in webview. To load the pdf file from url you need to use the google drive link. Download source code from here.

android open pdf file programmatically


activity_main.xml

<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <WebView
        android:layout_width="match_parent"
        android:id="@+id/webview"
        android:layout_height="match_parent">

    </WebView>

    <ProgressBar
        android:layout_width="wrap_content"
        android:id="@+id/progressbar"
        android:layout_centerInParent="true"
        android:layout_height="wrap_content" />


</RelativeLayout>


MainActivity.java


package com.deepshikha.openpdf;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
    WebView webview;
    ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = (WebView)findViewById(R.id.webview);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        webview.getSettings().setJavaScriptEnabled(true);
        String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
        webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);

        webview.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {
                // do your stuff here
                progressbar.setVisibility(View.GONE);
            }
        });

    }
}

Monday, July 10, 2017

Video Demo:





Show the viewpager with the boundaries of previous and next page in android programmatically. In this example I am using viewpager with fragments to show the left and right boundaries.Download source code from here

android viewpager multiple pages on screen


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff">

    <android.support.v4.view.ViewPager

        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="400dp"
        android:layout_centerInParent="true" />

</RelativeLayout>
MainActivity.java
package com.deepshikha.viewpager;

import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseArray;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends FragmentActivity {

    ViewPager pager;
    MyPageAdapter obj_adapter;
    String str_device;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();


    }

    private void init() {
        pager = (ViewPager) findViewById(R.id.viewpager);
        differentDensityAndScreenSize(getApplicationContext());
        List<Fragment> fragments = getFragments();
        pager.setAdapter(obj_adapter);
        pager.setClipToPadding(false);


        if (str_device.equals("normal-hdpi")){
            pager.setPadding(160, 0, 160, 0);
        }else if (str_device.equals("normal-mdpi")){
            pager.setPadding(160, 0, 160, 0);
        }else if (str_device.equals("normal-xhdpi")){
            pager.setPadding(160, 0, 160, 0);
        }else if (str_device.equals("normal-xxhdpi")){
            pager.setPadding(180, 0, 180, 0);
        }else if (str_device.equals("normal-xxxhdpi")){
            pager.setPadding(180, 0, 180, 0);
        }else if (str_device.equals("normal-unknown")){
            pager.setPadding(160, 0, 160, 0);
        }else {

        }

        obj_adapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
        pager.setPageTransformer(true, new ExpandingViewPagerTransformer());
        pager.setAdapter(obj_adapter);
    }

    class MyPageAdapter extends FragmentPagerAdapter {

        private List<Fragment> fragments;

        public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {

            super(fm);

            this.fragments = fragments;

        }

        @Override

        public Fragment getItem(int position) {

            return this.fragments.get(position);

        }

        @Override

        public int getCount() {

            return this.fragments.size();

        }

    }

    private List<Fragment> getFragments() {

        List<Fragment> fList = new ArrayList<Fragment>();

        fList.add(MyFragment.newInstance("Fragment 1",R.drawable.imags));
        fList.add(MyFragment.newInstance("Fragment 2",R.drawable.image1));
        fList.add(MyFragment.newInstance("Fragment 3",R.drawable.image2));
        fList.add(MyFragment.newInstance("Fragment 4",R.drawable.image3));
        fList.add(MyFragment.newInstance("Fragment 5",R.drawable.image4));

        return fList;

    }

    public int differentDensityAndScreenSize(Context context) {
        int value = 20;
        String str = "";
        if ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
            switch (context.getResources().getDisplayMetrics().densityDpi) {
                case DisplayMetrics.DENSITY_LOW:
                    str = "small-ldpi";
                    // Log.e("small 1","small-ldpi");
                    value = 20;
                    break;
                case DisplayMetrics.DENSITY_MEDIUM:
                    str = "small-mdpi";
                    // Log.e("small 1","small-mdpi");
                    value = 20;
                    break;
                case DisplayMetrics.DENSITY_HIGH:
                    str = "small-hdpi";
                    // Log.e("small 1","small-hdpi");
                    value = 20;
                    break;
                case DisplayMetrics.DENSITY_XHIGH:
                    str = "small-xhdpi";
                    // Log.e("small 1","small-xhdpi");
                    value = 20;
                    break;
                case DisplayMetrics.DENSITY_XXHIGH:
                    str = "small-xxhdpi";
                    // Log.e("small 1","small-xxhdpi");
                    value = 20;
                    break;
                case DisplayMetrics.DENSITY_XXXHIGH:
                    str = "small-xxxhdpi";
                    //Log.e("small 1","small-xxxhdpi");
                    value = 20;
                    break;
                case DisplayMetrics.DENSITY_TV:
                    str = "small-tvdpi";
                    // Log.e("small 1","small-tvdpi");
                    value = 20;
                    break;
                default:
                    str = "small-unknown";
                    value = 20;
                    break;
            }

        } else if ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
            switch (context.getResources().getDisplayMetrics().densityDpi) {
                case DisplayMetrics.DENSITY_LOW:
                    str = "normal-ldpi";
                    // Log.e("normal-ldpi 1","normal-ldpi");
                    str_device = "normal-ldpi";
                    value = 82;
                    break;
                case DisplayMetrics.DENSITY_MEDIUM:
                    // Log.e("normal-mdpi 1","normal-mdpi");
                    str = "normal-mdpi";
                    value = 82;
                    str_device = "normal-mdpi";
                    break;
                case DisplayMetrics.DENSITY_HIGH:
                    // Log.e("normal-hdpi 1","normal-hdpi");
                    str = "normal-hdpi";
                    str_device = "normal-hdpi";
                    value = 82;
                    break;
                case DisplayMetrics.DENSITY_XHIGH:
                    //Log.e("normal-xhdpi 1","normal-xhdpi");
                    str = "normal-xhdpi";
                    str_device = "normal-xhdpi";
                    value = 90;
                    break;
                case DisplayMetrics.DENSITY_XXHIGH:
                    // Log.e("normal-xxhdpi 1","normal-xxhdpi");
                    str = "normal-xxhdpi";
                    str_device = "normal-xxhdpi";
                    value = 96;
                    break;
                case DisplayMetrics.DENSITY_XXXHIGH:
                    //Log.e("normal-xxxhdpi","normal-xxxhdpi");
                    str = "normal-xxxhdpi";
                    str_device = "normal-xxxhdpi";
                    value = 96;
                    break;
                case DisplayMetrics.DENSITY_TV:
                    //Log.e("DENSITY_TV 1","normal-mdpi");
                    str = "normal-tvdpi";
                    str_device = "normal-tvmdpi";
                    value = 96;
                    break;
                default:
                    // Log.e("normal-unknown","normal-unknown");
                    str = "normal-unknown";
                    str_device = "normal-unknown";
                    value = 82;
                    break;
            }
        } else if ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
            switch (context.getResources().getDisplayMetrics().densityDpi) {
                case DisplayMetrics.DENSITY_LOW:
                    str = "large-ldpi";
                    // Log.e("large-ldpi 1","normal-ldpi");
                    value = 78;
                    break;
                case DisplayMetrics.DENSITY_MEDIUM:
                    str = "large-mdpi";
                    //Log.e("large-ldpi 1","normal-mdpi");
                    value = 78;
                    break;
                case DisplayMetrics.DENSITY_HIGH:
                    //Log.e("large-ldpi 1","normal-hdpi");
                    str = "large-hdpi";
                    value = 78;
                    break;
                case DisplayMetrics.DENSITY_XHIGH:
                    // Log.e("large-ldpi 1","normal-xhdpi");
                    str = "large-xhdpi";
                    value = 125;
                    break;
                case DisplayMetrics.DENSITY_XXHIGH:
                    //Log.e("large-ldpi 1","normal-xxhdpi");
                    str = "large-xxhdpi";
                    value = 125;
                    break;
                case DisplayMetrics.DENSITY_XXXHIGH:
                    // Log.e("large-ldpi 1","normal-xxxhdpi");
                    str = "large-xxxhdpi";
                    value = 125;
                    break;
                case DisplayMetrics.DENSITY_TV:
                    //Log.e("large-ldpi 1","normal-tvdpi");
                    str = "large-tvdpi";
                    value = 125;
                    break;
                default:
                    str = "large-unknown";
                    value = 78;
                    break;
            }

        } else if ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
            switch (context.getResources().getDisplayMetrics().densityDpi) {
                case DisplayMetrics.DENSITY_LOW:
                    // Log.e("large-ldpi 1","normal-ldpi");
                    str = "xlarge-ldpi";
                    value = 125;
                    break;
                case DisplayMetrics.DENSITY_MEDIUM:
                    // Log.e("large-ldpi 1","normal-mdpi");
                    str = "xlarge-mdpi";
                    value = 125;
                    break;
                case DisplayMetrics.DENSITY_HIGH:
                    //Log.e("large-ldpi 1","normal-hdpi");
                    str = "xlarge-hdpi";
                    value = 125;
                    break;
                case DisplayMetrics.DENSITY_XHIGH:
                    // Log.e("large-ldpi 1","normal-hdpi");
                    str = "xlarge-xhdpi";
                    value = 125;
                    break;
                case DisplayMetrics.DENSITY_XXHIGH:
                    // Log.e("large-ldpi 1","normal-xxhdpi");
                    str = "xlarge-xxhdpi";
                    value = 125;
                    break;
                case DisplayMetrics.DENSITY_XXXHIGH:
                    // Log.e("large-ldpi 1","normal-xxxhdpi");
                    str = "xlarge-xxxhdpi";
                    value = 125;
                    break;
                case DisplayMetrics.DENSITY_TV:
                    //Log.e("large-ldpi 1","normal-tvdpi");
                    str = "xlarge-tvdpi";
                    value = 125;
                    break;
                default:
                    str = "xlarge-unknown";
                    value = 125;
                    break;
            }
        }

        return value;
    }
}

myfragment_layout.xml
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="250dp"
    android:layout_height="250dp"
    android:background="#EAEAEA"
    android:orientation="vertical">

    <TextView

        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"

        />

    <ImageView
        android:id="@+id/iv_image"
        android:scaleType="fitXY"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
MyFragment.java
package com.deepshikha.viewpager;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by deepshikha on 6/7/17.
 */
public class MyFragment extends Fragment {

    View view;
    ImageView iv_image;

    public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
    public static final String IMAGE = "EXTRA_IMAGE";

    public static final MyFragment newInstance(String message, int int_image)

    {

        MyFragment f = new MyFragment();

        Bundle bdl = new Bundle(1);
        bdl.putString(EXTRA_MESSAGE, message);
        bdl.putInt(IMAGE, int_image);

        f.setArguments(bdl);

        return f;

    }

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        String message = getArguments().getString(EXTRA_MESSAGE);
        int int_image = getArguments().getInt(IMAGE);

        view = inflater.inflate(R.layout.myfragment_layout, container, false);

        TextView messageTextView = (TextView) view.findViewById(R.id.textView);

        ImageView iv_image = (ImageView) view.findViewById(R.id.iv_image);

        iv_image.setImageResource(int_image);
        messageTextView.setText(message);

        return view;

    }

}
ExpandingViewPagerTransformer.java:
package com.deepshikha.viewpager;

import android.os.Build;
import android.support.v4.view.ViewPager;
import android.view.View;

import android.os.Build;
import android.support.v4.view.ViewPager;
import android.view.View;

/**
 * Created by Qs on 16/5/30.
 */
public class ExpandingViewPagerTransformer implements ViewPager.PageTransformer {

    public static final float MAX_SCALE = 1.0f;
    public static final float MIN_SCALE = 0.8f;

    @Override
    public void transformPage(View page, float position) {

        position = position < -1 ? -1 : position;
        position = position > 1 ? 1 : position;

        float tempScale = position < 0 ? 1 + position : 1 - position;

        float slope = (MAX_SCALE - MIN_SCALE) / 1;
        float scaleValue = MIN_SCALE + tempScale * slope;
        page.setScaleX(scaleValue);
        page.setScaleY(scaleValue);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            page.getParent().requestLayout();
        }
    }
}