片段方向句柄AsyncTask

时间:2017-09-26 11:23:44

标签: android

我尝试在片段中编写asynctask,以便可以解决方向困境。到目前为止,asynctask工作正常,但与屏幕相关的进度条,屏幕更改,未显示。 我在下面附上了我的代码。 屏幕旋转,进度条和文本视图隐藏

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

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.a_fragment, container, false);
    unbinder = ButterKnife.bind(this, view);
    setRetainInstance(true);
    return view;
}

@OnClick(R.id.btn)
public void onViewClicked() {
    Log.w(TAG, "onBtn clicked");
    new URLAsyncTask().execute();

}


@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
        progressBar.setVisibility(View.VISIBLE);
        tvProgress.setVisibility(View.VISIBLE);
        progressValue = savedInstanceState.getInt("value");
        System.out.println(progressValue);
        progressBar.setProgress(progressValue);
        String rcv = savedInstanceState.getString("value2");
        tvProgress.setText(rcv);

    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("value", progressBar.getProgress());
    outState.putString("value2", tvProgress.getText().toString());
}

private class URLAsyncTask extends AsyncTask<Void, Integer, String> {
    @Override
    protected void onPreExecute() {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected String doInBackground(Void... voids) {
        String result = null;

        for (int i = 0; i <= 20; i++) {
            SystemClock.sleep(500);
            System.out.println("Loading..... " + i);
            publishProgress(i);
        }

        result = "A dummy";

        return result;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressBar.setProgress(values[0]);
        progressValue = values[0];
        tvProgress.setText("Loading .. at % ".concat(String.valueOf(progressValue)));
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.d(TAG, "onPostExecute() : s : " + s);
        System.out.println(TAG + " " + progressValue);
        if (progressValue == 20) {
            tvProgress.setText("LOADING 100 % DONE");
            progressBar.setVisibility(View.GONE);
        }
    }
}

} 一点帮助将受到高度赞赏

1 个答案:

答案 0 :(得分:0)

我不太了解您的问题,但我认为您在片段中遇到设备方向问题,AsynTask正在重新执行并显示错误的百分比。 如果我是对的:然后使用AsynTask,试试这个:

  

AsynTaskLoader

enter image description here 你也可以在Udacity的Android开发者课程上找到一些高质量的教程, (自由) https://www.udacity.com/course/android-basics-networking--ud843