Cara menampilkan progressbar di android studio

Tutorial Android

Cara menampilkan progressbar di android studio

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent" android:layout_height="match_parent">

<ProgressBar

android:id="@+id/pBar"

style="?android:attr/progressBarStyleHorizontal"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="100dp"

android:layout_marginTop="200dp"

android:minHeight="50dp"

android:minWidth="200dp"

android:max="100"

android:indeterminate="false"

android:progress="0" />

<TextView

android:id="@+id/tView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@+id/pBar"

android:layout_below="@+id/pBar" />

<Button

android:id="@+id/btnShow"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="130dp"

android:layout_marginTop="20dp"

android:text="Start Progress"

android:layout_below="@+id/tView"/>

</RelativeLayout>

 

MainActivity.java

package com.example.progressbarexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.os.Handler;

import android.view.View;

import android.widget.Button;

import android.widget.ProgressBar;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private ProgressBar pgsBar;

private int i = 0;

private TextView txtView;

private Handler hdlr = new Handler();

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

pgsBar = (ProgressBar) findViewById(R.id.pBar);

txtView = (TextView) findViewById(R.id.tView);

Button btn = (Button)findViewById(R.id.btnShow);

btn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

i = pgsBar.getProgress();

new Thread(new Runnable() {

public void run() {

while (i < 100) {

i += 1;

// Update the progress bar and display the current value in text view

hdlr.post(new Runnable() {

public void run() {

pgsBar.setProgress(i);

txtView.setText(i+"%");

}

});

try {

// Sleep for 200 milliseconds to show the progress slowly.

Thread.sleep(200);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}).start();

}

});

}

}

 

 

Tinggalkan Balasan

Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *