如何在片段中显示 ProgressDialog 栏?

How to display ProgressDialog bar within a fragment?

我想在从片段执行的 AsyncTask 期间显示 ProgressDialog。 我面临的问题是在 AsyncTask 期间不显示进度对话框,我不知道为什么。

这是 AsyncTask:

public class RankTask extends AsyncTask<Void, Void, ArrayList<RowRank>> {

    private ProgressDialog pDialog;
    private Context context;

    public RankTask(Context context) {
        super();
        this.context = context;

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(context);
        pDialog.setMessage("Loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();

    }

    @Override
    protected ArrayList<RowRank> doInBackground(Void... params) {

        IDBInteraction interaction = new DBInteraction(
                Connection.getConnection());

        return interaction.getRank();
    }

    @Override
    protected void onPostExecute(ArrayList<RowRank> result) {

        pDialog.dismiss();
        super.onPostExecute(result);
    }

}

这里是执行AsyncTask的Fragment:

public class RankFragment extends Fragment {

private TableLayout tableLayout;
private static float SIZE_TEXT = 20;

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

    View rootView = inflater.inflate(
            com.example.testintro.R.layout.fragment_rank, container, false);
    tableLayout = (TableLayout) rootView
            .findViewById(R.id.table_rank_layout);
    tableLayout.setStretchAllColumns(true);
    tableLayout.bringToFront();

    RankTask task = new RankTask(getActivity());
    try {

        createTable(task.execute().get());

    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    return rootView;
}

这是 Activity 的代码行,其中提交了片段:

private void changeActivity(Button button, final Fragment fragment) {
    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager
                    .beginTransaction();
            fragmentTransaction.replace(R.id.container, fragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

        }
    });

与进度对话框或片段无关 唯一错误的是你正在使用

task.execute().get()

这将在必要时等待计算完成,然后检索其结果。

因为它 运行 在主线程上你不能使用任何视图删除 get() 它应该可以正常工作

我猜..这是由于'context'问题..正确传递上下文..

Added this code at your Fragment..

   public Context context;
    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);
        context = activity;
    }