2012年5月21日 星期一

Handler-- ProgressBar

Handler
參考:http://www.vogella.com/articles/AndroidPerformance/article.html





res/layout/main.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Handler" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="4dip" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Progress" 
        android:onClick="startProgress"/>

</LinearLayout>

*******************************

main.java:


public class Cq_Handler_vogella01Activity extends Activity {
    /** Called when the activity is first created. */
private Handler mHandler;
private ProgressBar mProgressBar;
private Button mBtn;
private TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
        mBtn = (Button) findViewById(R.id.button1);
        tv = (TextView) findViewById(R.id.textView);
        
        mHandler = new Handler();
        mBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startProgress();
}
});
    }
    
    public void startProgress () {
    //Do something long
    Runnable runnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i<= 10; i++) {
final int value = i;
try {
Thread.sleep(2000);
}catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.post(new Runnable () {// 用來更新 View

@Override
public void run() {
// TODO Auto-generated method stub
mProgressBar.setProgress(value);
tv.setText("the value = " + value );
}
});
}
}
};
new Thread(runnable).start();
    }
}

沒有留言:

張貼留言