androidでタイマーとプログレスバーを併用
休日って
会社に出社して仕事をしないけどうまくバランスを調整できないのでなにすればいいのか結構悩む…
プログレスバーを使用して
時間の流れを制御する
実装
画面
※ボタンとプログレスバーを1つずつ配置
コード
package jp.mshige1979.app.sampleprogress1; import android.os.Handler; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends ActionBarActivity { private Button btn1; private ProgressBar prog1; private int count = 0; private MyTimerTask timerTask = null; private Timer timer = null; private Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn1 = (Button)findViewById(R.id.btn1); prog1 = (ProgressBar)findViewById(R.id.prog1); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 稼働中の場合は止める if(null != timer){ timer.cancel(); timer = null; } // タイマーインスタンスを作成 timer = new Timer(); // タイマータスクインスタンスを作成 timerTask = new MyTimerTask(); // タイマースケジュールを設定 timer.schedule(timerTask, 0, 10); // カウンタを初期化して設定 count = 0; prog1.setMax(300); prog1.setProgress(count); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } // タイマータスク用のクラス class MyTimerTask extends TimerTask { @Override public void run() { handler.post( new Runnable() { public void run() { count++; prog1.setProgress(count); if(count >= prog1.getMax()){ timer.cancel(); timer = null; } } }); } } }
結果