Using Kotlin to implement Android Simple Demo and comparing JAVA implementation to analyze specific syntax differences (2)

Using Kotlin to implement Android Simple Demo and comparing JAVA implementation to analyze specific syntax differences (2)

Before writing, the previous article simply realized the creation of Kotlin project files, and recorded the differences between the default generated code and the JAVA implementation. This article enumerates the differences between the coding of the whole Demo and the JAVA grammar.

The Demo effect is as follows: Head Rotary Graph + RecyclerView

Project address: git@github.com:M075097/kotlin_android_demo.git

1. Page layout, still using XML layout, the code is as follows

activity_main.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">

    <!-- Header Title Bar titlebar-->
    <RelativeLayout
        android:id="@+id/linearlayout_topbar_kotlindemo"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="@color/colorPrimary">

        <ImageView
            android:id="@+id/imageview_topbar_back"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:src="@drawable/ic_back"/>

        <TextView
            android:id="@+id/textview_first"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="Demo Display page"/>
    </RelativeLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager_kotlindemo"
        android:layout_width="match_parent"
        android:layout_height="120dp"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview_kotlindemo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

2. MainActivity.kt code is as follows

package com.yunzhongjun.weiyang.kotlindemo

import android.os.Bundle
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.yunzhongjun.weiyang.kotlindemo.data.BaseItemData
import com.yunzhongjun.weiyang.kotlindemo.data.ItemNormalData
import com.yunzhongjun.weiyang.kotlindemo.data.ItemTitleData

//Inherited from the parent AppCompatActivity implementation interface View.OnClickListener to compare JAVA implementation to class MainActivity extends AppCompatActivity implementations View.OnClickListener {}
class MainActivity : AppCompatActivity(), View.OnClickListener {
var textView: TextView? = null//Variable declaration - needs to be initialized. To initialize to null, you must use type A?
var mRecyclerView: RecyclerView? = null
var mViewPager: ViewPager? = null
var backButton: ImageView? = null
//var mDataList: List<BaseItemData>? = null;
var mDataList: MutableList<BaseItemData>? = null;//After the ArrayList declaration in Kotlin, you can't add or delete any more elements, you need to use MutableList instead. Generic use is similar to JAVA
var adapter: MyRecyclerViewAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)//Call the overridden method in the parent class, as in JAVA
    setContentView(R.layout.activity_main)
    initData()
    initView()
}

//Method Statement
private fun initData() {
    var titleData: ItemTitleData? = null
    var normalData: ItemNormalData? = null
    mDataList = mutableListOf<BaseItemData>()
    for (i in 1..4) {// for loop
        titleData = ItemTitleData()
        titleData.title = "Category title" + i
        mDataList!!.add(titleData)//When using mDataList.add(), an error is reported because the type declared by mDataList is A?. To use it, you need A?, as A?, or an instance of A?, after confirming that it is not empty!, Kotlin will convert A?, intelligently, to A?.
        for (j in 1..5) {
            normalData = ItemNormalData();
            normalData.itemDes = "type" + i + "lower:" + "entry" + j
            normalData.itemIconPath = null;
            mDataList!!.add(normalData)
        }
    }
}

private fun initView() {
    textView = findViewById(R.id.textview_first) as TextView //Strong transition type, compared with JAVA's (AA)A implementation of Kotlin directly using AA as A
    mRecyclerView = findViewById(R.id.recyclerview_kotlindemo) as RecyclerView
    mViewPager = findViewById(R.id.viewpager_kotlindemo) as ViewPager
    backButton = findViewById(R.id.imageview_topbar_back) as ImageView

    backButton?.setOnClickListener(this)
    var str: String = "Kotlin Demo page"
    textView?.setText(str)//T Must there be one here? Because A? And A are not the same type.

    //init ViewPager
    var viewPagerAdapter:MyViewPagerAdapter = MyViewPagerAdapter(3);//New objects do not need to use the new analogy JAVA grammar: MyViewPagerAdapter viewPagerAdapter = new MyViewPagerAdapter(3);
    mViewPager?.adapter = viewPagerAdapter //The original set/get method in an object can be assigned directly using A.property as long as it meets the standard setter and getter naming rules. The underlying method is still to call setter and getter methods.

    //init RecyclerView
    var layoutManager: LinearLayoutManager = LinearLayoutManager(this)
    mRecyclerView?.layoutManager = layoutManager;
    adapter = MyRecyclerViewAdapter(mDataList)
    //adapter?.setDataList(mDataList)
    mRecyclerView?.adapter = adapter
}
//Interface method override
override fun onClick(v: View?) {
    when (v?.id) {
        R.id.imageview_topbar_back -> {
            this.finish()
        }
        else -> {
            //TODO nothing
        }
    }
    //when syntax implementation is analogous to JAVA
  /*  switch(v.getId()){
        case R.id.imageview_topbar_back:
                break;
        default:
            break;
    }*/

}
}

The differences between Kotlin and JAVA codes can be seen by comparing the above specific codes as follows

  • 1. Class inheritance is different from the syntax of implementing interfaces. There is no need to use extends and implements to distinguish declarations and unify them in Kotlin.

Kotlin inherits the parent class and implements the interface as follows:

class MainActivity : AppCompatActivity(), View.OnClickListener {
    //code what you want!   
}

Java implements the following:

class MainActivity extends AppCompatActivity implements View.OnClickListener{
    //code what you want!
}
  • 2. When inheriting a parent class, if the parent class does not have an explicit constructor implementation, you need to add () after the parent class name to indicate the constructor that uses its default null parameter.

The code is as follows

class MainActivity : AppCompatActivity()//Here we need ()
  • 3. Variables are declared in different ways. Variables use var keyword and constant use val keyword. Take the TextView declaration in Android as an example.

The TextView variable in Kotlin is declared as follows:

var textView: TextView? = null // variable declaration -- needs to be initialized, and you must use type A if you want to initialize to null.

If used directly, it can be as follows (no need to add a logo)
var textView1:TextView = findViewById(R.id.textview_first) as TextView

Compare life in Java as follows:

TextView textView;
  • 4. Declarations of methods are different

The format in Kotlin is as follows: private fun function Name (a:A,b:B): C {}

* Kotlin uses the fun keyword declaration.
* Method parameter is (variable name: variable type)
* If the parameters are more than one, use "," separately.
* The return value type declaration is declared by adding ":" before the body of the method and after the parameters.
* Methods in Kotlin can also use private, public declarations

Compare the format in JAVA to private C functional Name (A, B) {}

In Kotlin's specific use, the following assemblies are declared

var mDataList: List<*>? = ArrayList<*>();

In use mDataList? The following error is reported in. add().

smartcast is not impossibleļ¼Œbeacuse "mDataList" is mutable property that could have been changed by this time 

So here you need to use the collection type MutableList provided in Kotlin, declared as follows

var mDataList: MutableList<BaseItemData>? = null;//Code excerpt from MainActivity.kt

Initialize as follows

mDataList = mutableListOf<BaseItemData>()//Code excerpt from MainActivity.kt

Use the following

 mDataList?.add(normalData)//Code excerpt from MainActivity.kt
  • 6.for recycling is different

The code used in Kotlin is as follows

 for (j in 1..5) {//Here 1.5 corresponds to an array [1,2,3,4,5]
           //do what you want
        }

One way to compare JAVA is as follows

int[] aa = new int[]{1,2,3,4,5};
for(int i:aa){
    //do what you want
}
  • 7. Strong transitions are used differently. TextView's strongest transitions are as follows

The strong turn in Kotlin is as follows

//findViewById () returns to View type by default. To be declared TextView type textView reception, you need to do the following forcing
textView = findViewById(R.id.textview_first) as TextView //Strong transition type, compared with JAVA's (AA)A implementation of Kotlin directly using AA as A

Comparing JAVA implementations are as follows

textView = (TextView)findViewById(R.id.textview_first);
  • 8. Object instantiation differences, instantiation comparison of MyViewPagerAdapter customized in the Demo

Objects in Kotlin are instantiated as follows. The biggest difference is that the keyword "new" is not required.

var viewPagerAdapter:MyViewPagerAdapter = MyViewPagerAdapter(3)

Object instantiation in JAVA

MyViewPagerAdapter viewPagerAdapter = new MyViewPagerAdapter(3);
  • 9. The difference between the use of setter-compliant and getter-compliant naming methods in the original object --- a comparison of setter-compliant and getter-compliant methods of setting Adapter with native ViewPager

Setting Adapter in Kotlin Project can be set directly by using attribute assignment similar to js

mViewPager?.adapter = viewPagerAdapter

The use in JAVA is as follows

mViewPager.setAdapter(viewPagerAdapter);
  • 10. Grammatical differences of switch

Kotlin uses when to implement a switch grammar structure similar to that in JAVA. Specifically, it compares the implementation in onclick (View view) {} in MainActivity.kt.

when (v?.id) {
        R.id.imageview_topbar_back -> {
            this.finish()
        }
        else -> {//Equivalent to default in switch
            //TODO nothing
        }
    }

The implementation in JAVA is as follows

switch(v.getId()){
        case R.id.imageview_topbar_back:
                break;
        default:
            break;
    }

The MyViewPager Adapter definition code used by ViewPager is as follows

MyViewPagerAdapter.kt

package com.yunzhongjun.weiyang.kotlindemo

import android.support.v4.view.PagerAdapter
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView

/**
 * Created by weiyang on 2017/7/11 0011.
 */
class MyViewPagerAdapter(pageCount: Int) : PagerAdapter() {

private var pageCount: Int

init {
    this.pageCount = pageCount;
}

override fun isViewFromObject(view: View?, `object`: Any?): Boolean {
    return view == `object`;
}

override fun getCount(): Int {
    return pageCount
}

override fun destroyItem(container: ViewGroup?, position: Int, `object`: Any?) {
    container?.removeView(`object` as View)
    //super.destroyItem(container, position, `object`)
}

override fun instantiateItem(container: ViewGroup?, position: Int): Any {
    var imageView: ImageView? = ImageView(container?.context);
    var resId: Int
    when (position) {
        0 -> {
            resId = R.drawable.image_2
        }
        1 -> {
            resId = R.drawable.image_3
        }
        2 -> {
            resId = R.drawable.image_4
        }
        else -> {
            resId = R.drawable.image_aa
        }
    }
    imageView?.setImageDrawable(container?.context?.resources?.getDrawable(resId))
    var layoutParams: ViewGroup.LayoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
    imageView?.layoutParams = layoutParams
    imageView?.scaleType =ImageView.ScaleType.CENTER_CROP
    container?.addView(imageView)
    return imageView!!
}
}

Comparing JAVA implementations, we can see that this class of implementations are constructed differently from JAVA implementations.

  • The difference between constructor implementations is that the class declaration in Kotlin can keep up with the default constructor in () after the class name, but other operations of the default constructor need to be placed in init {}, which is called the primary constructor.

Specific and detailed reference on the main and sub-constructors of Class in Kotlin http://www.runoob.com/kotlin/kotlin-class-object.html

Kotlin is implemented as follows

class MyViewPagerAdapter(pageCount: Int) : PagerAdapter() {

    private var pageCount: Int

    init {
        this.pageCount = pageCount;
    }
    //Other methods of overwriting
    //...
}

JAVA is implemented as follows

public class MyViewPagerAdapter extends PagerAdapter{
    private int pageCount;
    public MyViewPagerAdapter(int pageCount){
        //Sup (); // Hidden Call Family Default Constructor
        this.pageCount = pageCount;
    }
}

4. Other differences between Kotlin and JAVA grammars that can be directly referred to in the Demo

  • 1. Implementation of static methods (refer specifically to BaseItemData.kt in this Demo)
    • static KEYWORD DECLARATION IN JAVA
    • In Kotlin, you need to use companion object {} including related methods
  • 2. Implementation of Enumeration Classes

The code is as follows: BaseItemData.kt

      package com.yunzhongjun.weiyang.kotlindemo.data

/**
 * Created by weiyang on 2017/7/11 0011.
 */
abstract class BaseItemData {
abstract fun getItemType(): ItemType

 enum class ItemType(typeValue: Int) {
    TypeNormal(0),
    TypeTitle(1),
    Unsupport(2);

    var typeValue: Int

    init {
        this.typeValue = typeValue;
    }

    companion object {
        //Analog static methods in JAVA
        fun getTypeValue(typeValue: Int): ItemType {
            for (value in values()) {
                if (value.typeValue == typeValue) {
                    return value;
                }
            }
            return Unsupport;
        }
    }

}
}
  • 3 When an instance uses a declaration similar to A?(A is a specific class name), it may make an error when calling some attributes, and the display type is nullable, then it can use the assertion A!! When confirming that it is not null, it can convert A?To A?!

The corresponding schematic code is as follows

var a:A? = null
a!!.property//Relevant property calls

Keywords: Android Java xml git

Added by fri on Fri, 14 Jun 2019 03:00:48 +0300