如果不先滚动,则不会显示RecyclerView项目中的图像

时间:2019-06-24 08:13:32

标签: java android android-recyclerview picasso

我从WordPress页面API发出了一些请求,以获取一些内容,对于每种内容,我都会得到一张图片。然后将它们显示在RecyclerView上。但是,如果不先滚动RecyclerView,然后开始逐个显示,它们就不会显示。

这里是NewsActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_news);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Window w = getWindow();
        w.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        w.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    back_button = findViewById(R.id.toolbar_back_button);
    back_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

    toolbarTxt = findViewById(R.id.tolbar_text_view);
    toolbarTxt.setText("News");

    recyclerView = findViewById(R.id.news_recyclerview);

    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(mAdapter);
    recyclerView.setHasFixedSize(true);

    ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
            connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
            merrLajmet();
    } else {
        Toast.makeText(this, "You do not have internet connection", Toast.LENGTH_SHORT).show();
    }

}

这是我获取内容的方式。

public void merrLajmet(){

    Uri baseUri = Uri.parse(NEWS_REQUEST_URL);
    Uri.Builder uriBuilder = baseUri.buildUpon();

    JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(
            Request.Method.GET, uriBuilder.toString(), null, new Response.Listener<JSONArray>() {

        @Override
        public void onResponse(JSONArray response) {
            listLajmet = Query.shfaqLajmet(response);

            for (Lajmi lajmi : listLajmet) {
                merrFoton(lajmi);
            }
            mAdapter.setLajmi(listLajmet);
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            // Error
        }
    });

    if (listLajmet.isEmpty()) {
        MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
    }
}

然后从特定内容获取照片。

public void merrFoton(final Lajmi lajmi) {

    Uri baseUri = Uri.parse(IMAGE_REQUEST_URL);
    Uri.Builder uriBuilder = baseUri.buildUpon();
    uriBuilder.appendPath(String.valueOf(lajmi.getFeatureMedia()));

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
            Request.Method.GET, uriBuilder.toString(), null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            String imageUrl = Query.shfaqFoton(response);
            if (imageUrl == ""){
                imageUrl = String.valueOf(R.drawable.news_photo1);
            }

            lajmi.setImage(imageUrl);
            //mAdapter.setLajmi(listLajmet);
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            //Toast.makeText(NewsActivity.this, "Nuk ka te image " +
                    //error.networkResponse.toString(), Toast.LENGTH_SHORT).show();
        }
    });

    MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
}

最后,这是我的适配器类。

public class LajmiAdapter extends RecyclerView.Adapter<LajmiAdapter.MyViewHolder>{

    private List<Lajmi> mLajmiList = new ArrayList<>();
    private Context ctx;

    public LajmiAdapter(Context ctx) {
        this.ctx = ctx;
    }

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        TextView mTitle, mCategory;
        ImageView mImage,mColor;

        public MyViewHolder(View itemView) {
            super(itemView);

            itemView.setOnClickListener(this);

            mTitle = itemView.findViewById(R.id.news_text_view_titulli);
            mCategory = itemView.findViewById(R.id.news_text_view_kategoria);

            mImage = itemView.findViewById(R.id.news_image_main);
            mColor = itemView.findViewById(R.id.news_image_small);
        }

        @Override
        public void onClick(View v) {

            int position = getAdapterPosition();

            Lajmi lajmi = mLajmiList.get(position);

            Intent intent = new Intent(ctx, SinglenewsActivity.class);

            intent.putExtra("title", lajmi.getTitle());
            intent.putExtra("category", lajmi.getCategory());
            intent.putExtra("image", lajmi.getImage());
            intent.putExtra("color",lajmi.getColor());
            intent.putExtra("description",lajmi.getDescription());

            ctx.startActivity(intent);
        }
    }

    @Override
    public LajmiAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View itemView;
        itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
        return new LajmiAdapter.MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(LajmiAdapter.MyViewHolder holder, int position) {

        Lajmi lajmi = mLajmiList.get(position);
        holder.mTitle.setText(lajmi.getTitle());

        Picasso.get()
                .load(lajmi.getImage())
                .resize(400, 300)
                .onlyScaleDown()
                .into(holder.mImage);
    }

    public void setLajmi(List<Lajmi> lajmiList) {
        mLajmiList = lajmiList;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        if(mLajmiList == null)
            return 0;
        else
            return mLajmiList.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }
}

打开NewsActivity时,我希望所有图像都显示在RecyclerView项上,而无需先滚动。

2 个答案:

答案 0 :(得分:0)

滚动列表时,它会获取更新的项目,因此会获取从服务器获取的图像的更新列表。我认为您在这里错过了一个notifyDataSetChanged通话。

@Override
public void onResponse(JSONObject response) {
    String imageUrl = Query.shfaqFoton(response);
    if (imageUrl == ""){
        imageUrl = String.valueOf(R.drawable.news_photo1);
    }

    lajmi.setImage(imageUrl);
    // Add the notifyDataSetChanged here
    mAdapter.notifyDataSetChanged();
}

但是,在这种情况下,当您一张一张地获取图像时,每次获取图像时,都会通知适配器,因此RecyclerView将相应地重新加载。当您每次滚动浏览项目,每次每次调用notifyDataSetChanged()时从服务器获取新图像时,列表都会到达顶部,这很烦人。

我想建议以不同的方式实现整个图像的获取。获取要首先下载的图像数。然后获取所有图像URL,并将其保存在列表中。完成下载所有图像URL后,请致电notifyDataSetChanged

希望有帮助!

答案 1 :(得分:0)

notifyDataSetChanged():通知附加的观察者基础数据已更改,任何反映该数据集的View均应刷新自身。(https://developer.android.com/reference/android/widget/BaseAdapter

如果要一张一张地获取图像,刷新视图可能不是最佳解决方案。如果您不希望每次下载新图像时都将其滚动到页面顶部,则可以使用notifyItemRangeInserted(int positionStart, int itemCount)

也请看看这个question