activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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="#EEE" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Do some stuff" /> <ProgressBar android:id="@+id/progressBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:visibility="gone" /> </LinearLayout> |
MainActivity.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package com.phaisarn.ktapplication import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // when button is clicked, start the task button.setOnClickListener { v -> Thread(Runnable { // display the indefinite progressbar this@MainActivity.runOnUiThread( Runnable { progressBar.visibility = View.VISIBLE } ) // performing some dummy time taking operation try { Thread.sleep(3000) } catch (e: InterruptedException) { e.printStackTrace() } // when the task is completed, make progressBar gone this@MainActivity.runOnUiThread( Runnable { progressBar.visibility = View.GONE } ) }).start() } } } |