Created
June 20, 2016 11:52
-
-
Save ivanovsuper/437675eb44754713107329ddb1ef6020 to your computer and use it in GitHub Desktop.
Timer в ListView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ivanovsuper.timerprogress; | |
import android.content.Context; | |
import android.view.LayoutInflater; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.ArrayAdapter; | |
import android.widget.ImageButton; | |
import android.widget.ProgressBar; | |
import android.widget.TextView; | |
import java.util.ArrayList; | |
import java.util.Timer; | |
import java.util.TimerTask; | |
public class MyAdapter extends ArrayAdapter<String> { | |
private final Timer timer; | |
private ArrayList<TimerTask> mTimers; | |
private final Context context; | |
private final String[] values; | |
public MyAdapter(Context context, String[] values) { | |
super(context, R.layout.list_item, values); | |
this.context = context; | |
this.values = values; | |
mTimers = new ArrayList<>(values.length); | |
timer = new Timer("MyAdapterTimer"); | |
} | |
//Вызвать при onPause фрагмента/активити | |
public void cancelTimers(){ | |
for(TimerTask task: mTimers){ | |
task.cancel(); | |
} | |
timer.cancel(); | |
} | |
@Override | |
public View getView(final int position, View convertView, ViewGroup parent) | |
{ | |
LayoutInflater inflater = (LayoutInflater) context | |
.getSystemService(Context.LAYOUT_INFLATER_SERVICE); | |
View rowView = inflater.inflate(R.layout.list_item, parent, false); | |
final ProgressBar progress = (ProgressBar) rowView.findViewById(R.id.progress_bar); | |
TextView time = (TextView) rowView.findViewById(R.id.time_text); | |
final TextView percentage = (TextView) rowView.findViewById(R.id.percentage_text); | |
percentage.setText(values[position]); | |
ImageButton button1 = (ImageButton) rowView.findViewById(R.id.button_1); | |
ImageButton button2 = (ImageButton) rowView.findViewById(R.id.button_2); | |
button2.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
//todo отменить предыдущее выполнение или блокировать кнопку | |
timer.scheduleAtFixedRate(mTimers.get(position),0,1000);//раз в секунду | |
} | |
}); | |
mTimers.add(new TimerTask() { | |
@Override | |
public void run() { | |
progress.post(new Runnable() { | |
@Override | |
public void run() { | |
//todo проверить на 100% остановить таймер mTimers.get(position).cancel() | |
progress.setProgress(progress.getProgress()+1); | |
} | |
}); | |
} | |
}); | |
return rowView; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment