Tuesday, 5 December 2017

Simple example of using ViewPager in Kotlin | Android

Though Kotlin has lot of massive features to speedup the development time, here is the simple example of using ViewPager in Android. In Kotlin we don't need to declare and initialize Views. We can simply access the id of Views from xml.

Ex:
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:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.guna.kotlinapplication.MainActivity">

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

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
MainActivity.kt
import android.os.Bundle
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.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        setupViewPager(pager)
        tabs.setupWithViewPager(pager)
    }

    private fun setupViewPager(pager: ViewPager?) {
        val adapter = Adapter(supportFragmentManager)

        val f1 = BlankFragment.newInstance("One")
        adapter.addFragment(f1, "TAB 1")

        val f2 = BlankFragment.newInstance("Two")
        adapter.addFragment(f2, "TAB 2")

        val f3 = BlankFragment.newInstance("Three")
        adapter.addFragment(f3, "TAB 3")

        pager?.adapter = adapter
    }

    private class Adapter(manager: FragmentManager) : FragmentPagerAdapter(manager) {
        val fragments = ArrayList()
        val titles = ArrayList()
        override fun getItem(position: Int): Fragment = fragments.get(position)

        override fun getCount(): Int = fragments.size

        override fun getPageTitle(position: Int): CharSequence? = titles.get(position)

        fun addFragment(fragment: Fragment, title: String) {
            fragments.add(fragment)
            titles.add(title)
        }
    }
}
BlankFragment.kt
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_blank.view.*

class BlankFragment : Fragment() {
    var text = ""

    companion object {
        fun newInstance(text: String): BlankFragment {
            val fragment = BlankFragment()
            val bundle = Bundle()
            bundle.putString("Text", text)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        text = arguments?.get("Text").toString()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_blank, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.textView.setText(text)
    }
}

Did you noticed, we never declare pager nor initialized, instead we directly accessed it from activity_main.
In BlankFragment also, we didn't declare and initialize textView

And also, unless Java, default constructor will come with class name itself; like Adapter(manager: FragmentManager).

So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current Activity is java, don't worry, you can create your next Activity in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.

Here is the full video tutorial

Interesting right?


If you are really interested in this code, then please share this post with your friends.


Simple example of using RecyclerView in Kotlin | Android

Simple example of using Spinner in Kotlin | Android

Simple example of using CheckBox in Kotlin | Android

Using Button in Kotlin | Android

Getting Started on Kotlin

Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You



Thursday, 30 November 2017

Simple example of using RecyclerView in Kotlin | Android

Though Kotlin has lot of massive features to speedup the development time, here is the simple example of using RecyclerView in Android. In Kotlin we don't need to declare and initialize RecyclerView. We can simply access the id of RecyclerView from xml.

Ex :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.guna.kotlinapplication.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</android.support.constraint.ConstraintLayout>


We can simply access id of RecyclerView from above xml in kotlin file.
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.setHasFixedSize(true)
recyclerView.adapter = Adapter(myStrings, this)

Here is the Adapter.kt class.
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.item.view.*

/**
 * Created by Guna on 30-11-2017.
 */
class Adapter(val strings: Array<String>, val activity: MainActivity) : RecyclerView.Adapter<Adapter.ViewHolder>() {

    override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
        holder?.bind(strings[position], activity)
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder =
            ViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.item, parent, false))

    override fun getItemCount(): Int = strings.size

    class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
        fun bind(string: String, activity: MainActivity) {
            itemView.textView.setText(string)
            itemView.setOnClickListener{
                view ->  activity.fromAdapter(string)
            }
        }
    }
}

And Here is the MainActivity.kt class.
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    val myStrings = arrayOf("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
            "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen")
    val paint = Paint()

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

        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.setHasFixedSize(true)
        recyclerView.adapter = Adapter(myStrings, this)

        val callback = object : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
            override fun onMove(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, target: RecyclerView.ViewHolder?): Boolean {
                val fromPosition = viewHolder!!.adapterPosition
                val toPosition = target!!.adapterPosition

                val fromString = myStrings[fromPosition]
                val toString = myStrings[toPosition]

                myStrings[fromPosition] = toString
                myStrings[toPosition] = fromString
                recyclerView?.adapter?.notifyItemMoved(fromPosition, toPosition)
                return true
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder?, direction: Int) {
                if (direction == ItemTouchHelper.LEFT) {
                    Toast.makeText(this@MainActivity, myStrings[viewHolder!!.adapterPosition] + " Left Swiped", LENGTH_LONG).show()
                } else if (direction == ItemTouchHelper.RIGHT) {
                    Toast.makeText(this@MainActivity, myStrings[viewHolder!!.adapterPosition] + " Right Swiped", LENGTH_LONG).show()
                }
                recyclerView.adapter.notifyDataSetChanged()
            }

            override fun onChildDraw(c: Canvas?, recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
                if (dX > 0) {
                    paint.color = Color.GREEN
                    val rect = Rect(viewHolder!!.itemView!!.left, viewHolder.itemView.top, dX.toInt(), viewHolder.itemView.bottom)
                    c?.drawRect(rect, paint)
                } else if (dX < 0) {
                    paint.color = Color.RED
                    val rect = Rect(viewHolder!!.itemView.right.plus(dX).toInt(), viewHolder.itemView.top, viewHolder.itemView.right, viewHolder.itemView.bottom)
                    c?.drawRect(rect, paint)
                }
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
            }
        }

        val helper = ItemTouchHelper(callback)
        helper.attachToRecyclerView(recyclerView)
    }

    fun fromAdapter(string: String) {
        Toast.makeText(this, string, LENGTH_LONG).show()
    }
}

Did you noticed, we never declare recyclerView nor initialized, instead we directly accessed it from activity_main.
In ViewHolder also, we didn't declare and initialize textView

And also, unless Java, default constructor will come with class name itself; like Adapter(val strings: Array, val activity: MainActivity).

So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current Activity is java, don't worry, you can create your next Activity in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.

Here is the full video tutorial

Interesting right?


If you are really interested in this code, then please share this post with your friends.


Simple example of using Spinner in Kotlin | Android

Simple example of using CheckBox in Kotlin | Android

Using Button in Kotlin | Android

Getting Started on Kotlin

Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You



Tuesday, 28 November 2017

Simple example of using Spinner in Kotlin | Android

Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Spinner in Android. In Kotlin we don't need to declare and initialize Spinner. We can simply access the id of Spinner from xml.

Ex :
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

        //String array.
        val myStrings = arrayOf("One", "Two", "Three", "Four", "Five")
        
        //Adapter for spinner
        mySpinner.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, myStrings)
        
        //item selected listener for spinner
        mySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(p0: AdapterView<*>?) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                Toast.makeText(this@MainActivity, myStrings[p2], LENGTH_LONG).show()
            }

        }
    }
}

Did you noticed, we never declare myCheckBox nor initialized, instead we directly accessed it from activity_main.
And also there is no new keyword while ArrayAdapter or implementing OnItemSelectedListener.

So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current Activity is java, don't worry, you can create your next Activity in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.

Here is the full video tutorial

Interesting right?


If you are really interested in this code, then share this post with your friends.


Simple example of using CheckBox in Kotlin | Android


Using Button in Kotlin | Android


Getting Started on Kotlin


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You



Monday, 27 November 2017

Simple example of using CheckBox in Kotlin | Android

Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Button in Android. In Kotlin we don't need to declare and initialize CheckBox. We simply access the id of CheckBox from Kotlin file.

Ex :
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

        myCheckBox.setOnCheckedChangeListener { view, isChecked ->
            Toast.makeText(this, isChecked.toString(), LENGTH_LONG).show()
        }
    }
}

Did you noticed, we never declare myCheckBox nor initialized, instead we directly accessed it from activity_main.
And inside setOnCheckedChangeListener method, we didn't implement `onCheckedChanged` interface.

So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current Activity is java, don't worry, you can create your next Activity in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.

Here is the full video tutorial

Interesting right?


If you are really interested in this code, then share this post with your friends.


Using Button in Kotlin | Android


Getting Started on Kotlin


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You



Thursday, 16 November 2017

Basic data types of KOTLIN and simple examples.

In this section we describe the basic types used in Kotlin: numbers, characters, booleans, arrays, and strings.

Numbers

Kotlin handles numbers in a way close to Java, but not exactly the same. For example, there are no implicit widening conversions for numbers, and literals are slightly different in some cases.

Kotlin provides the following built-in types representing numbers (this is close to Java):

Type Bit width
Double 64
Float 32
Long 64
Int 32
Short 16
Byte 8


We can declare data types in KOTLIN as following way.
var a: Int = 0 //int var, we can reassign at runtime or anywhere in the code. 
val a:Int =0 //int val, val cannot reassign.
var a = 0 //int var
val a = 0 //int val

var a = 10.10 //Double
var a = 10.10f //Float
var a = 10.10F //Float

var a = 10L //Long

//You can use underscores to make number constants more readable:
val oneMillion=1_000_000

Every number type supports the following conversions:

toByte(): Byte

toShort(): Short

toInt(): Int

toLong(): Long

toFloat(): Float

toDouble(): Double

toChar(): Char

Operations


Here is the complete list of bitwise operations (available for Int and Long only):
  1. shl(bits) – signed shift left (Java's <<)
  2. shr(bits) – signed shift right (Java's >>)
  3. ushr(bits) – unsigned shift right (Java's >>>)
  4. and(bits) – bitwise and
  5. or(bits) – bitwise or
  6. xor(bits) – bitwise xor
  7. inv() – bitwise inversion

Ex:

var x = 1 shl 2
var x = 1 shr 2
var x = 1 ushr 2
var x = 1 and 2
var x = 1 or 2
var x = 1 xor 2
var x = 1.inv()

Also we have int() instead of ++ and dec() instead of --.

Ex:

var x = a.inc()

Characters

Characters are represented by the type Char
var c = 'a'.

Booleans

The type Boolean represents booleans, and has two values: true and false.
var b = true

Strings

Strings are represented by the type String. Strings are immutable. var s = "Hello Kotlin"

Interesting right?


If you are really interested in this code, then share this post with your friends.


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You



Thursday, 9 November 2017

Using Button in Kotlin | Android

Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Button in Android.
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private var count: Int = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        myButton.setOnClickListener({
            count = count.inc()
            Toast.makeText(this, "Clicked Count " + count, LENGTH_LONG).show()
            myButton.setText("Click again")
        })
    }
}

Did you noticed, Here we used colon(:) instead of extends keyword, but here we used parentheses at end of the AppCompatActivity.
And we initialized count as Int var, where Int is one of the data type in Kotlin used to declare int variable from Java, and var defines count as variable, means, can be reinitialized at run time.
And we never declare myButton nor initialized, instead we directly accessed it from activity_main.
And inside setOnClickListener method, we didn't implement `OnClickListener` interface.

So, in simple accessing of button itself, we omitted near 10 lines of code. So imagine about full length project, near 40% of time is saved right?
So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current Activity is java, don't worry, you can create your next Activity in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.

Here is the full video tutorial

Interesting right?


If you are really interested in this code, then share this post with your friends.


Getting Started on Kotlin


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You



Thursday, 2 November 2017

Getting Started on Kotlin

Kotlin is now an official language on Android. Kotlin is expressive, concise, extensible, powerful, and a joy to read and write. It has wonderful safety features in terms of nullability and immutability.

If you're interested in using Kotlin, it's easy to get started because it works side by side with Java and C++ on Android. So you can keep your existing code, continue to use the various Android libraries, and incrementally add Kotlin code to your project. Unlike almost any other language, Kotlin is a drop-in replacement you can use bi-directionally—you can call into the Java language from Kotlin, and you can call into Kotlin from the Java language.

Of course, IDE support is also crucial, and we have it. Android Studio is built upon IntelliJ IDEA, an IDE built by JetBrains—the same company that created the Kotlin language. The JetBrains team has been working for years to make sure Kotlin works great with IntelliJ IDEA. So we're inheriting all their hard work. Starting with Android Studio 3.0, tooling support for Kotlin is bundled directly into Android Studio.

Create a new project with Kotlin

Using Kotlin with a new project requires just one extra click in the New Project wizard:
  1. In Android Studio, click File > New > New Project. Or if you've just opened Android Studio and see the Welcome to Android Studio window, click Start a new Android Studio project.
  2. On the first screen, check Include Kotlin support. That's the only difference.
  3. Click Next and continue through the wizard until you're done.



Add Kotlin to an existing project

If you want to add Kotlin code to an existing project, simply click File > New and select one of the various Android templates. If you don't see the list of templates in this menu, first open the Project window and select your app module.

Convert existing Java code to Kotlin code

In Android Studio 3.0, open a Java file and select Code > Convert Java File to Kotlin File.

Or, create a new Kotlin file (File > New > Kotlin File/Class), and then paste your Java code into that file—when prompted, click Yes to convert the code to Kotlin. You can check Don't show this dialog next time, which makes it easy to dump Java code snippets into your Kotlin files.

Use Android APIs with Kotlin

Kotlin provides complete interoperability with the Java language, so calling the Android APIs often looks exactly like the matching Java code. Except now you can combine those method calls with Kotlin's syntax features.

Here are a few examples of what it looks like to call Android APIs in Kotlin, compared to the same code in Java language:

Declare Activity in Java

public class MyActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);
  }
}

Declare Activity in Kotlin

class MyActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity)
  }
}

On-click listener in Java

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    //TODO: Do your code
  }
});

On-click listener in Kotlin

val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener {
  //TODO: Do your code
}

Item click listener in Java

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
    = new BottomNavigationView.OnNavigationItemSelectedListener() {
  @Override
  public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
      case R.id.navigation_home:
        mTextMessage.setText(R.string.title_home);
        return true;
      case R.id.navigation_dashboard:
        mTextMessage.setText(R.string.title_dashboard);
        return true;
    }
    return false;
  }
};

Item click listener in Kotlin

private val mOnNavigationItemSelectedListener
    = BottomNavigationView.OnNavigationItemSelectedListener { item ->
  when (item.itemId) {
    R.id.navigation_home -> {
      mTextMessage.setText(R.string.title_home)
      return@OnNavigationItemSelectedListener true
    }
    R.id.navigation_dashboard -> {
      mTextMessage.setText(R.string.title_dashboard)
      return@OnNavigationItemSelectedListener true
    }
 }
 false
}

Here is the Get Started with Kotlin video.

Interesting right?


If you are really interested in this code, then share this post with your friends.


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You