更新android中方向更改的进度条

时间:2013-08-02 05:33:25

标签: android android-asynctask android-progressbar

我有一个片段,我正在片段上设置listview。

以下是代码:

public class AttachmentsFragment extends Fragment {

ListView lstView = null;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //retains fragment instance across Activity re-creation
    setRetainInstance(true);
    objects = new ArrayList<AttachModel>();

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View view = null;

    view = inflater.inflate(R.layout.tab_attachment, container, false);

    lstView = (ListView) view.findViewById(R.id.listViewAttachment);
    adapter = new AttachAdapter(getActivity(), 0, 0, objects);
    lstView.setAdapter(adapter);

    return view;
}

}

在适配器中,我有一个进度条和一个textview来显示进度条的进度。用于启动和停止进度条的按钮

public class AttachAdapter extends ArrayAdapter<AttachModel> implements OnClickListener {

Context context;
ArrayList<AttachModel> objects = new ArrayList<AttachModel>();

AttachModel info;

//Activity act;

AttachModel model;

public AttachmentsAdapter(Context context, int resource,
        int textViewResourceId, ArrayList<AttachmentsModel> objects) {
    super(context, textViewResourceId, textViewResourceId, objects);

    this.context = context;
    this.objects = objects;

} 

// no. of attachments available
@Override
public int getCount() {

    return objects.size();
}

@Override
public AttachmentsModel getItem(int position) {

    return objects.get(position);
}

@Override
public long getItemId(int position) {

    return position;
}

@Override
public View getView(int position, View convertView, final ViewGroup parent) {

    View row = convertView;
    ViewHolder holder = null;

    if(null == row) {
      LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      row = inflater.inflate(R.layout.attachment_list_item, parent, false);


      //textview for showing progress
      holder.textViewProgress = (TextView) row.findViewById(R.id.txtViewPg);

      //progress bar to show the progress
      holder.progressBar = (ProgressBar) row.findViewById(R.id.pgBar);
      holder.progressBar.setTag(position);

      holder.textViewProgress.setVisibility(TextView.VISIBLE);
      holder.img_view_fileIcon.setVisibility(ImageView.VISIBLE);

      holder.progressBar.setVisibility(ProgressBar.VISIBLE);

      //to start stop the progress bar                
      holder.button = (Button)row.findViewById(R.id.img_btn_download);
      holder.button.setVisibility(Button.VISIBLE);

      holder.button.setTag(position);
      holder.button.setOnClickListener(this);

      row.setTag(holder);


    } else {
      holder = (ViewHolder) row.getTag();

    }


    return row;
}

private class ViewHolder {
    TextView textViewProgress;
    ProgressBar progressBar;
    Button button;

    boolean downloadFlag = false;

}

@Override
public void onClick(View v) {

    View vParent=(View) v.getParent();

    ViewHolder tempHolder = null;

    tempHolder=(ViewHolder) vParent.getTag();

    //toggle button like functionality
    if(!tempHolder.downloadFlag) {

        tempHolder.downloadFlag = true;
        tempHolder.progressBarStatus = 0;

        async = new AsyncTaskAttachments(tempHolder, objects.get(Integer.parseInt(v.getTag().toString())).getFilePath());

        tempHolder.async.execute();

        objects.get((Integer)tempHolder.progressBar.getTag()).setAsyncTask(tempHolder.async);

    }else {

        tempHolder.downloadFlag = false;
        tempHolder.progressBar.setProgress(0);

        tempHolder.textViewProgress.setVisibility(TextView.GONE);
        tempHolder.textViewProgress.setText("");
        tempHolder.progressBarStatus = 0;

        tempHolder.async.cancel(true);



    }

}

public class AsyncTaskAttachments extends AsyncTask<Void, Void, Void> {

    private ViewHolder holder;

    public AsyncTaskAttachments(ViewHolder holder, String filePath) {
        this.holder = holder;
        this.filePath = filePath;           

    }

    public void attach(Activity act) {
        this.act = act;
    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub


        holder.progressBarStatus = 0;

        for(int i=0; i<=10; i++) {
            try {
                Thread.sleep(1000);
                holder.progressBarStatus = i*10;


                    if(isCancelled()) {
                        break;
                    }


                publishProgress();
            }catch (Exception e) {
                // TODO: handle exception
            }

        }

        return null;
    }

    /* (non-Javadoc)
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

    }

    /* (non-Javadoc)
     * @see android.os.AsyncTask#onPreExecute()
     */
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

            holder.progressBarStatus = 0;

            holder.textViewProgress.setText("" + holder.progressBarStatus + "%");

            holder.progressBar.setProgress(holder.progressBarStatus);


    }

    /* (non-Javadoc)
     * @see android.os.AsyncTask#onProgressUpdate(Progress[])
     */
    @Override
    protected void onProgressUpdate(Void... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);

                // TODO Auto-generated method stub
                holder.progressBar.setProgress(holder.progressBarStatus);
                holder.textViewProgress.setText("" + holder.progressBarStatus + "%");



    }


}

}

注意:这只是为了表明我这样做的方式。这只是一瞥。我需要知道我是否走在正确的轨道上。

在方向更改时,进度条无法保留并从方向更改的位置开始进度。

提前致谢

3 个答案:

答案 0 :(得分:1)

当方向更改时,将重新创建您的活动(以及包含的片段)。所以你再次调用你的asyncTask,它将进度设置为零:

holder.progressBarStatus = 0;

解决方案:保存片段的onSaveInstanceState()中的进度,onCreateView()中的resotre使asyncTask使用此值进行初始进度设置。

答案 1 :(得分:0)

它完成了..对于所有面临这个问题的人或将来会面对这个问题。

不要尝试重新创建视图。 只需在onCreate()方法中填充listview一次。

因为,在保留片段时,只调用一次oncreate和ondestroy方法。因此,为了保持进度条的状态,将代码放在oncreate方法中。

答案 2 :(得分:0)

我知道这个问题很旧并且已经被回答,所以仅作记录:您可以使用viewmodel更改方向后保持进度条的状态。我在一个片段中有一个进度条,并且在按下按钮后激活了进度条。技巧是在进度条被激活时在视图模型中设置一个变量,并在片段的onCreatView方法中读取该变量。这样,进度条将继续执行与方向更改之前相同的操作(旋转/不旋转)。可以通过修改将其应用于其他情况。

Viewmodel:

// create livedata variable
private final MutableLiveData<Boolean> mIsProgressBarActive = new MutableLiveData<>();

// get status from viewmodel
public LiveData<Boolean> getProgressBarStatus() {return mIsProgressBarActive; }

// save status to viewmodel
public void setProgressBarStatus(boolean status) {
    mIsProgressBarActive.postValue(status);
}

onCreate片段:

super.onCreate(savedInstanceState);
mViewModel =  ViewModelProviders.of(getActivity()).get(yourViewModel.class);

onCreateview片段:

View content = inflater.inflate(R.layout.your_fragment, container, false);
ProgressBar progressBar = content.findViewById(R.id.progressbar);

// if it was spinning, keep progress bar spinning after orientation change
if(mViewModel.getProgressBarStatus().getValue()) {
        progressBar.setIndeterminate(true);
}

// activate progress bar and save its state to viewmodel
mButton.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           progressBar.setIndeterminate(true);
           mViewModel.setProgressBarStatus(true);
       }
});

Xml布局:

<ProgressBar
android:id="@+id/progressbar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"/>