Created
July 18, 2016 09:16
-
-
Save aldakur/fb60b4200b13d1a64c45981bbd94cb32 to your computer and use it in GitHub Desktop.
Writing in a TextView numbers from 1 to 10, and display the progress bar during the process
This file contains hidden or 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
import android.os.AsyncTask; | |
import android.support.v7.app.AppCompatActivity; | |
import android.os.Bundle; | |
import android.text.method.ScrollingMovementMethod; | |
import android.view.View; | |
import android.widget.Button; | |
import android.widget.ProgressBar; | |
import android.widget.TextView; | |
public class PorgressBarExample extends AppCompatActivity { | |
Button boton; | |
TextView textView; | |
ProgressBar progressBar; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
boton = (Button) findViewById(R.id.boton); | |
textView = (TextView) findViewById(R.id.textview); | |
progressBar = (ProgressBar) findViewById(R.id.progressbar); | |
progressBar.setVisibility(View.INVISIBLE); | |
textView.setMovementMethod(new ScrollingMovementMethod()); // android:scrollbars="vertical" kodeari kaso egiteko | |
boton.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
MyTask task = new MyTask(); | |
task.execute(); | |
} | |
}); | |
} | |
public void cargarDatos(String datos){ | |
textView.append(datos+"\n"); | |
} | |
private class MyTask extends AsyncTask<String, String, String>{ | |
@Override | |
protected void onPreExecute() { | |
super.onPreExecute(); | |
cargarDatos("Inicio de carga"); | |
progressBar.setVisibility(View.VISIBLE); | |
} | |
@Override | |
protected String doInBackground(String... params) { | |
for(int i=0; i<=10; i++){ | |
//No podemos cambiar la interface en doInBackground pq es el hilo principal. Por eso debemos de usar publishProgress dentro de el | |
publishProgress("Numero: "+i); | |
try { | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
return "Terminamos"; | |
} | |
@Override | |
protected void onPostExecute(String s) { | |
super.onPostExecute(s); | |
cargarDatos(s); | |
progressBar.setVisibility(View.INVISIBLE); | |
} | |
@Override | |
protected void onProgressUpdate(String... values) { | |
cargarDatos(values[0]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment