Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 進度條 ProgressBar 最基礎用法

進度條是開發時經常會用到的元件,這裡用最簡單的例子把它的基本操作走一遍。

版面配置 XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        />
    <ProgressBar
        android:id="@+id/firstBar"
        android:layout_width="200dip"
        android:layout_height="wrap_content"
        android:visibility="gone"
    />
    <ProgressBar
        android:id="@+id/secondBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
    />
    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="begin"
    />
</LinearLayout>

ProgressbarActivity.java

package com.progress;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class ProgressbarActivity extends Activity {
    private ProgressBar firstBar = null;
    private ProgressBar secondBar = null;
    private Button myButton = null;
    private int i = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        firstBar = (ProgressBar) findViewById(R.id.firstBar);
        secondBar = (ProgressBar) findViewById(R.id.secondBar);
        myButton = (Button) findViewById(R.id.myButton);
        myButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (i == 0) {
                    firstBar.setVisibility(View.VISIBLE); // 設為可見
                    firstBar.setMax(150);                 // 設定最大值
                    secondBar.setVisibility(View.VISIBLE);
                } else if (i < firstBar.getMax()) {
                    firstBar.setProgress(i);              // 設定主進度條目前值
                    // 設定次進度條目前值,預設最大值 100 時即前進 1/10
                    firstBar.setSecondaryProgress(i + 10);
                } else {
                    firstBar.setVisibility(View.GONE);    // 設為不可見
                    secondBar.setVisibility(View.GONE);
                }
                i = i + 10;
            }
        });
        System.out.println(firstBar.getMax());
    }
}

透過 setVisibility 控制顯示、setMax 設定上限、setProgress 與 setSecondaryProgress 更新進度,就能輕鬆做出基本的進度條互動。

Copyright © Linux教程網 All Rights Reserved