這里為啥要用nit()方法寫按鈕的findViewById,而不是寫進OnCreate方法里面??
package com.example.progressbar1015;
import android.app.Activity;
import android.os.Bundle;
import android.os.Process;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private Button add;
private Button reduce;
private Button reset;
private TextView textView;
private ProgressBar progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 啟用窗口特征,啟用帶進度和不帶進度的進度條
requestWindowFeature(Window.FEATURE_PROGRESS);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main);
// 顯示兩種進度條
setProgressBarVisibility(true);
setProgressBarIndeterminate(false);
// 進度Max=10000;
setProgress(999);// 設置進度條的當前進度。
}
private void init() {
progress = (ProgressBar) findViewById(R.id.horiz);
add = (Button) findViewById(R.id.add);
reduce = (Button) findViewById(R.id.reduce);
reset = (Button) findViewById(R.id.reset);
textView = (TextView) findViewById(R.id.textView);
int first = progress.getProgress();
int second = progress.getSecondaryProgress();
// 獲取進度條的最大長度
int max = progress.getMax();
textView.setText("第一進度條百分比:" + (int) (first / (float) max * 100) + "%"
+ " ? ? " + " ? ? ? " + "第二進度條百分比:"
+ (int) (second / (float) max * 100) + "%");
add.setOnClickListener(this);
reduce.setOnClickListener(this);
reset.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.add: {
progress.incrementProgressBy(10);
progress.incrementSecondaryProgressBy(10);
break;
}
case R.id.reduce: {
progress.incrementProgressBy(-10);
progress.incrementSecondaryProgressBy(-10);
break;
}
case R.id.reset: {
progress.setProgress(50);
progress.setSecondaryProgress(80);
}
}
textView.setText("第一進度條百分比:"
+ (int) (progress.getProgress() / (float) progress.getMax() * 100)
+ "%"
+ " ? ? "
+ " ? ? ? "
+ "第二進度條百分比:"
+ (int) (progress.getSecondaryProgress()
/ (float) progress.getMax() * 100) + "%");
}
}
2016-10-15
寫成方法的形式,增加代碼的復用性, 也可以寫在onCreate() 方法,這樣寫就感覺代碼太臃腫。
2016-10-21
主要是為了好看哦,另外也可以多次使用
2016-10-15
你這段代碼有問題呀,你在onCreate()方法中沒有調用init()方法,不會執行init里面的初始化操作的。
在外部寫init方法主要是為了使代碼整潔更好維護。