In the previous blog, I wrote about val and var use and their differences. In this post, I am going to introduce you to the basic steps to write a program in Android with Kotlin. Just follow simple steps below:-
1)First, declare a string type variable. You can either use val or var for initializing your variable and keep in mind that if you are reinitializing a variable do not use val. write a simple line :-
var str=”Hello World” or
var str: String=”Hello World” or
val str=”Hello World” or
val str: String=”Hello World”
2)In second step, you have to add the textView element in activity_main.xml like below and give a unique id
<TextView
android:id=”@+id/textView”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintLeft_toLeftOf=”parent”
app:layout_constraintRight_toRightOf=”parent”
app:layout_constraintTop_toTopOf=”parent” />
3)In the MainActivity.kt. we will initialize a textview using findViewById method like below:-
var textview=findViewById(R.id.textView) as TextView
4)In the last, you have to assign string value inside textview using text function.
textview.text=str
5)You are done. Now just run your program. Below is a full code snippet for you to see.
package adapter.manasvi.com.simpleproject
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class HelloWorld : AppCompatActivity() {
val str:String="Hello World"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var textview=findViewById(R.id.textView) as TextView
textview.text=str
}
}
You will get an Output as “Hello World”.
Feel free to try this code and comment below.