1. Creating New Project in Kotlin
- Open Android Studio.
- Go to File => New => New Project.Give Name To your application. Then, check Include Kotlin Support and click next button.
- Select minimum SDK you need. However, we have selected 21 as minimum SDK. Then, click next button.
- Then, select Empty Activity => click next => click finish.
2. Here we take Progress Bar (Horizontal) and Button.As in below xml layout.
main_activity.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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.dharmendra.progressbar.MainActivity"> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="85dp" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/progressBar" android:layout_centerHorizontal="true" android:layout_marginTop="42dp" android:text="Button" /> </RelativeLayout>
3.MainActivity.kt
package com.dharmendra.progressbar import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import android.widget.Button import android.widget.ProgressBar class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Find view By Id for ProgressBar,Button val progressBar = findViewById<ProgressBar>(R.id.progressBar) as ProgressBar val btn = findViewById<Button>(R.id.button) as Button //On Click for Button btn.setOnClickListener { //Set button Clickable false to stop multiple Clicks at a time btn.isClickable = false //Here We Create one Thread to change Status of Progress bar var status = 0 //Initial status of Progress Bar Thread(Runnable { while (status < 100) { status += 1 //if error Occures than it will habdle in try-catch block. try { Thread.sleep(30) progressBar.setProgress(status) } catch (e: Exception) { Log.e("Error", e.message) } } //Set Button Clickable true after Progress Complete btn.isClickable = true }).start() } } }
Output:
No comments:
Post a Comment