Asynctask 和 RecyclerView 适配器中的 Android ProgressDialog

Posted

技术标签:

【中文标题】Asynctask 和 RecyclerView 适配器中的 Android ProgressDialog【英文标题】:Android ProgressDialog inside Asynctask and RecyclerView Adapter 【发布时间】:2017-10-24 09:36:32 【问题描述】:

伙计们,我的progressDialog 有点问题。它不能以正确的方式工作。我的 progressDialog 在 RecylerView 适配器内,因为我使用 Glide 加载了许多图片。这是我使用 Glide 时显示 progressDialog 的唯一方法 - 如果我将 progressDialog 移动到 Asynctask proExecute 并 postExecute 它仅在 doinBackground 作业正在执行和隐藏时显示。但 Glide 仍在加载图片。 正如我所写,我将其放入适配器并隐藏直到图片加载的解决方案工作很奇怪。有时当我运行应用程序时,我必须等到没有进度对话框的图片加载,有时它会显示很短的时间。如何解决?在我的情况下使用 progressDialog 的最佳方式是什么?

我的主要活动:

public class MainActivity extends AppCompatActivity 

    List<String> shopsNames;
    ArrayList<RowModel> rowModels;

    public Realm mRealm;
    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout toolbarLayout;
    @BindView(R.id.app_bar)
    AppBarLayout appBar;
    private ShopsAdapter adapter;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        ButterKnife.bind(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ConnectionDetector connectionDetector = new ConnectionDetector(this);
        if (!connectionDetector.isConnection()) 
            finish();
        

        ActivityCompat.requestPermissions(this, new String[]android.Manifest.permission.ACCESS_FINE_LOCATION, 123);



        rowModels = new ArrayList<>();
        shopsNames = new ArrayList<>();
        Realm.init(this);

        mRealm = Realm.getDefaultInstance();

        initCollapsingToolbar();

        Glide.with(getApplicationContext()).load(R.drawable.shoplogo).
                into((ImageView) findViewById(R.id.backdrop));

        adapter = new ShopsAdapter(MainActivity.this, shopsNames);

        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 2);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        AsyncTaskRetro asyncTaskRetro = new AsyncTaskRetro();
        asyncTaskRetro.execute();
    

    private class AsyncTaskRetro extends AsyncTask<Void, Void, Void> 

        @Override
        protected Void doInBackground(Void... voids) 

            PlacesAPI.Factory.getInstance().getPlaces().enqueue(new Callback<Places>() 

                @Override
                public void onResponse(Call<Places> call, Response<Places> response) 
                    for (int i = 0; i < response.body().getPosts().size(); i++) 
                        RowModel rowModel = new RowModel(response.body().getPosts().get(i).getNazwa(),
                                Double.parseDouble(response.body().getPosts().get(i).getSzer()),
                                Double.parseDouble(response.body().getPosts().get(i).getDlug()));
                        rowModels.add(rowModel);
                    
                    String oldName;
                    oldName = rowModels.get(0).getName();
                    shopsNames.add(rowModels.get(0).getName());

                    mRealm.beginTransaction();
                    mRealm.copyToRealm(rowModels);
                    mRealm.commitTransaction();

                    for (int j = 0; j < rowModels.size(); j++) 

                        if (rowModels.get(j).getName().equals(oldName)) 
                            continue;
                        
                        oldName = rowModels.get(j).getName();
                        shopsNames.add(rowModels.get(j).getName());
                    

                    //sortowanie listy z nazwami sklepow
                    Collections.sort(shopsNames);

                    adapter = new ShopsAdapter(MainActivity.this, shopsNames);
                    recyclerView.setAdapter(adapter);
                

                @Override
                public void onFailure(Call<Places> call, Throwable t) 

                
            );

            return null;
        
    

    private void initCollapsingToolbar() 
        final CollapsingToolbarLayout collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
        collapsingToolbar.setTitle(" ");
        AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
        appBarLayout.setExpanded(true);

        // hiding & showing the title when toolbar expanded & collapsed
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() 
            boolean isShow = false;
            int scrollRange = -1;

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) 
                if (scrollRange == -1) 
                    scrollRange = appBarLayout.getTotalScrollRange();
                
                if (scrollRange + verticalOffset == 0) 
                    collapsingToolbar.setTitle(getString(R.string.app_name));
                    isShow = true;
                 else if (isShow) 
                    collapsingToolbar.setTitle(" ");
                    isShow = false;
                
            
        );
    

我的适配器类:

public class ShopsAdapter extends RecyclerView.Adapter<ShopsAdapter.MyViewHolder> 

    Context mContext;
    List<String> shopsList;
    ProgressDialog progressDialog;

    public class MyViewHolder extends RecyclerView.ViewHolder 
        public ImageView thumbnail;

        public MyViewHolder(View view) 
            super(view);
            thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
        
    

    public ShopsAdapter(Context mContext, List<String> shopsList) 
        this.mContext = mContext;
        this.shopsList = shopsList;

        progressDialog = new ProgressDialog(mContext);
    

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) 
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.shop_card, parent, false);

        return new MyViewHolder(itemView);
    

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) 

        shopsList.get(position);
        try 
            progressDialog.show();
            progressDialog.setMessage("Czekaj...");
            String stringformat = String.format("http://www.wp.pl%s.png", shopsList.get(position));
            Glide.with(mContext).load(stringformat).listener(new RequestListener<String, GlideDrawable>() 
                @Override
                public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) 
                    Log.d("fsfsdf", e.getMessage());
                    return false;
                

                @Override
                public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) 
                    progressDialog.hide();
                    return false;
                
            ).centerCrop().fitCenter().into(holder.thumbnail);
         catch (Exception e) 
            Glide.with(mContext).load("http://www.wp.pl/Zabka.png").centerCrop().fitCenter().into(holder.thumbnail);
        

        holder.thumbnail.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 

                //Log.d("Nazwa sklepu: ", shopsList.get(position));
                Intent intent = new Intent(mContext, MapActivity.class);
                intent.putExtra("shopName", shopsList.get(position));
                mContext.startActivity(intent);
            
        );
    

    @Override
    public int getItemCount() 
        return shopsList.size();
    

【问题讨论】:

【参考方案1】:

最简单的方法是在 imageview 后面显示进度条。将 ImageView 和 ProgressBar 添加到 RelativeLayout。加载图像时,它将自动隐藏进度条。捷径:D

 <RelativeLayout
    android:layout_
    android:layout_>

    <ProgressBar
        android:layout_
        android:layout_
        android:layout_centerInParent="true" />

    <ImageView
        android:layout_
        android:layout_ />
</RelativeLayout>

只加载图片,不要对进度条做任何事情。

【讨论】:

很好,但是如何在图像加载完成时收到通知? 不需要。它看起来就像它的图像将被加载到它上面。 你能展示一下这个布局应该是什么样子吗?我很困惑,我无法想象它是如何工作的...... 我不相信它会起作用:) 但我先检查一下.. 不行。即使图像加载,progressDialog 仍然显示

以上是关于Asynctask 和 RecyclerView 适配器中的 Android ProgressDialog的主要内容,如果未能解决你的问题,请参考以下文章

NullPointerException 与 android AsyncTask 和 RecyclerView

Asynctask 和 RecyclerView 适配器中的 Android ProgressDialog

EndlessRecyclerOnScrollListener 与 Asynctask 的 Endless RecyclerView

Asynctask 崩溃 ViewPager RecyclerView (Android)

将 AsyncTask 与 RecyclerView 一起使用:没有结果,但 asynctask 似乎正在工作

Android:使用 Asynctask 时 Recyclerview 出现问题