Luke Batley Luke Batley - 1 month ago 7
Android Question

Android spin refresh button while reloading

Hi Does anyone know how to create a refresh button that when pressed it shows a loading spinner and then when its stopped goes back to the button?

heres what ive got so far

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//Check Preferences which sets UI

checkPreferences();
PostTask posttask;
posttask = new PostTask();
posttask.execute();

Button backbtn = (Button) findViewById(R.id.backbtn);

//Listening to button event
backbtn.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
//Starting a new Intent
Intent previousScreen = new Intent(getApplicationContext(), ChooseTeamActivity.class);
ChosenMethod = "null";
SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("ChosenMethod", ChosenMethod);
editor.commit();
previousScreen.putExtra("FullData", fulldata);
startActivity(previousScreen);

}
});

Button refresh = (Button) findViewById(R.id.refresh);

//Listening to button event
refresh.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
// TODO Auto-generated method stub

PostTask posttask;
posttask = new PostTask();
posttask.execute();

}


});


heres the function i want it to load

public class PostTask extends AsyncTask<Void, String, Boolean> {


@Override
protected Boolean doInBackground(Void... params) {
boolean result = false;


loadFixtures();
publishProgress("progress");
loadResultsFeed();
publishProgress("progress");
loadNewsFeed();
publishProgress("progress");
return result;
}

protected void onProgressUpdate(String... progress) {
StringBuilder str = new StringBuilder();
for (int i = 1; i < progress.length; i++) {
str.append(progress[i] + " ");

}
}

@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.v("BGThread", "begin fillin data");
FillData();

}
}

Answer

in your xml file make

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/refresh"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleSmall"
        android:layout_width="40dip"
        android:layout_height="40dip"
        android:layout_margin="10dip"
        android:visibility="gone" >
    </ProgressBar>
</RelativeLayout>

then in your PostTask onPreExecute method

findViewById(R.id.refresh).setVisibility(View.GONE);
findViewById(R.id.progress).setVisibility(View.VISIBLE);

and on your OnPostExecute

findViewById(R.id.refresh).setVisibility(View.VISIBLE);
findViewById(R.id.progress).setVisibility(View.GONE);