Develop APP from java to kotlin (1)

#Use Kotlin to write code initially and replace Butterknife in the project#
(remember -kotlin configuration, Butterknife replacement, View layer usage issues)

1. Development tools android studio-2.3.3

2. Add the following code to the build.gradle file in the project root directory

buildscript {
    ext.kotlin_version = '1.2.21'
  
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

Then add the following code to the build.gradle of the app module

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

The above completes the preparation for writing kotlin below android studio 3.0 (android studio 3.0 is said to come with it, not sure if it has not been upgraded)

3. Replace the Butterknife library in the project.

The plugin added in the build.gradle file of the app module is used to replace Butterknife.

apply plugin: 'kotlin-android-extensions'

No need to findById, no need to BindView, you can directly use the id of the View to operate the View in the project, the principle is as follows (taken from the network Baidu can check)

Kotlin Android Extensions is another plugin developed by the Kotlin team that allows us to develop programs with less code. Currently only bindings for views are included. The plugin automatically creates a lot of properties to give us direct access to views in XML. So there is no need for you to find these views in the layout. The name of the View we use is the id from the corresponding view, so we need to be very careful when taking the id, which will be a very important part of our class. The types of these controls are also from XML, so we don't need to do additional type conversions. Kotlin Android Extensions do not need to rely on other additional libraries. It is only layered by the plugin group, which is used to generate the code needed to work, and only depends on the Kotlin standard library. The working principle of Kotlin Android Extensions is: The plugin will call the function instead of any property, such as getting the view and having a cache function, so that the view will not be re-fetched every time the property is called. This cache device is only valid in Activity or Fragment. if it was added in an extension function

code manipulation

In the Activity/Fragment class that needs to be used, the layout source of the plugin needs to be set, that is, the following code

import kotlinx.android.synthetic.main.activity_repository.*

Among them, kotlinx.android.synthetic.main. is a fixed path, and there will be automatic prompts for completion. It does not need to be changed. Just replace the following activity_repository with the current layout.
image.png

When using the control, directly use the id of the View and then refer to the properties, such as setting the visibility property of the View and the click event Xml

 <TextView
            android:id="@+id/repository_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/activity_horizontal_margin"
            android:layout_marginTop="@dimen/activity_horizontal_margin"
            android:textSize="20sp"
            tools:text="@string/name"/>

kotlin

// layoutContent 是id
repository_name.visibility = View.GONE
// 设置点击事件
repository_name.setOnClickListener {
            Toast.makeText(this, "这是个点击事件", Toast.LENGTH_LONG).show()
        }

java

// 原生方法
// repositoryName是对象名称
repositoryName = (TextView)layout.findViewById(R.id.repository_name);
repositoryName.setVisibility(View.GONE);

checkEvent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             Toast.makeText(this, "这是个点击事件", Toast.LENGTH_LONG).show();   
            }
        });

// Butterknife使用
@BindView(R.id.repository_name)
TextView repositoryName;

@OnClick(R.id.repository_name)
public void nameOnclick(){
     Toast.makeText(this, "这是个点击事件", Toast.LENGTH_LONG).show();
    }

After adding the kotlin plugin, you can use the properties of the control by calling the id directly using the View. The commonly used methods such as setText() and setVisibility() directly use .text and .visibility

From the common property settings and click events alone, a lot of code can be reduced .

There is also a convenient syntax detail in kotlin, that is, there is no need for ";" after each line of code, each line of code is a statement, which grammatically controls the readability of the code.

Note that kotlin code cannot be written in java code, and java code can be written in kotlin code, and the two can call each other. Kotlin and java are two languages, this is understandable.

question

Question 1 :

When the kotlin-android-extensions plugin version is 1.1.4-3 , it does not support the use of include tags in XML . It can be used in version 1.2.21, but do not name the include ID when using the include tag , otherwise There will be an error that the control findById fails, and the called control returns NULL, although the kotlin built-in method is called later, it returns to normal.

   var i = layout.findViewById<TextView>(R.id.tv_title)

Question 2 :

There are things to pay attention to when using Fragment. When we use Butterknife , we can operate on View after calling bind.

        View layout = LayoutInflater.from(getActivity()).inflate(R.layout.activity_repository, null);
        ButterKnife.bind(this, layout);

The kotlin-android-extensions plugin will throw a NULL exception when using the view before the onCreateView method returns the view. The reason is that the Layout is not cached at this time, and the Layout will only be cached after the onCreateView method is executed . Then the initialization of many controls needs to be called within a method. According to the life cycle of the fragment, we can initialize the VIew in the two methods of onActivityCreated and onViewCreated, and the activity does not have this problem. As before, after executing the setContentView method, you can directly call the ID to operate the View.

setContentView(R.layout.activity_organization)

Question 3 :

The properties of the control mentioned earlier are used, and the text in the box is set in EditText according to the general setting logic

name_value.text = datdBean.consigneeName // 使用报错

The above code reports an error. The error log is type is String! but Editable! was expected . Obviously the type is wrong, which is embarrassing. It is not possible to use .attribute assignment in this place , and you need to directly call the unencapsulated API.

 name_value.setText(datdBean.consigneeName) //使用正常

There are still unsolved mysteries, and the documentation continues to be updated. . .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325889524&siteId=291194637