为什么我的“帖子”在 android recyclerview 中以不同的尺寸加载?

2023-12-22

好的,这就是我的回收视图显示我的“帖子”的方式。谁能告诉我为什么?我也会发布源代码。我尝试更改一些代码但没有成功。另外,当我滚动 RecyclerView 时,其中一些会调整为更小或更大的尺寸。感谢任何和所有的帮助!

片段_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#fff" />

</LinearLayout>

列表项.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/listItemLayout">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/yesButton"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:background="#00FF00" />

        <ImageButton
            android:id="@+id/noButton"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:background="#FF0000" />

    </LinearLayout>

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/image_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/placeholder" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:background="#509f9f9f"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="8"
            android:orientation="horizontal">

            <com.android.volley.toolbox.NetworkImageView
                android:id="@+id/thumbnail"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:scaleType="fitXY"
                android:src="@drawable/placeholder" />

            <TextView
                android:id="@+id/pUsername"
                android:layout_marginLeft="5dp"
                android:layout_marginStart="5dp"
                android:gravity="center_vertical"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="username" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/postMenu"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:background="#000"/>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

LruBitmapCache.java:

public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageCache {

    public LruBitmapCache(int maxSize) {
        super(maxSize);
    }

    public LruBitmapCache(Context context) {
        this(getCacheSize(context));
    }

    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight();
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }

    public static int getCacheSize(Context context) {
        final DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        final int screenWidth = displayMetrics.widthPixels;
        final int screenHeight = displayMetrics.heightPixels;
        final int screenBytes = screenWidth * screenHeight * 4;

        return screenBytes * 3;
    }

}

MyRecyclerAdapter.java:

public class MyRecyclerAdapter extends RecyclerView.Adapter<ListRowViewHolder> {

    private List<ListItems> listItemsList;
    private Context mContext;
    private ImageLoader mImageLoader;

    private int focusedItem = 0;

    public MyRecyclerAdapter(Context context, List<ListItems> listItemsList) {
        this.mContext = context;
        this.listItemsList = listItemsList;
    }

    @Override
    public ListRowViewHolder onCreateViewHolder(final ViewGroup viewGroup, int position) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
        ListRowViewHolder holder = new ListRowViewHolder(v);

        return holder;
    }

    @Override
    public void onBindViewHolder(final ListRowViewHolder listRowViewHolder, int position) {
        ListItems listItems = listItemsList.get(position);
        listRowViewHolder.itemView.setSelected(focusedItem == position);

        listRowViewHolder.getLayoutPosition();

        mImageLoader = MySingleton.getInstance(mContext).getImageLoader();

        listRowViewHolder.thumbnail.setImageUrl(listItems.getProfilePicture(), mImageLoader);
        listRowViewHolder.thumbnail.setDefaultImageResId(R.drawable.placeholder);

        listRowViewHolder.image_1.setImageUrl(listItems.getImage_1(), mImageLoader);
        listRowViewHolder.image_1.setDefaultImageResId(R.drawable.placeholder);

        listRowViewHolder.username.setText(Html.fromHtml(listItems.getUsername()));
    }

    public void clearAdapter() {
        listItemsList.clear();
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return (null != listItemsList ? listItemsList.size() : 0);
    }

}

MySingleton.java:

public class MySingleton {

    private static MySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mContext;

    private MySingleton(Context context) {
        mContext = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue, new LruBitmapCache(LruBitmapCache.getCacheSize(mContext)));
    }

    public static synchronized MySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }

}

ListRowViewHolder.java:

public class ListRowViewHolder extends RecyclerView.ViewHolder {

    protected NetworkImageView thumbnail;
    protected NetworkImageView image_1;
    protected ImageButton yes;
    protected ImageButton no;
    protected TextView username;
    protected LinearLayout recLayout;

    public ListRowViewHolder(View view) {
        super(view);
        this.thumbnail = (NetworkImageView) view.findViewById(R.id.thumbnail);
        this.image_1 = (NetworkImageView) view.findViewById(R.id.image_1);
        this.yes = (ImageButton) view.findViewById(R.id.yesButton);
        this.no = (ImageButton) view.findViewById(R.id.noButton);
        this.username = (TextView) view.findViewById(R.id.pUsername);
        this.recLayout = (LinearLayout) view.findViewById(R.id.listItemLayout);
        view.setClickable(true);
    }

}

FragmentHome.java:

public class FragmentHome extends Fragment {

    private final String postsUrl = "http://www.example.com/fetch_posts.php";

    private ProgressDialog progressDialog;

    private static final String TAG = "RecyclerViewExample";
    private List<ListItems> listItemsList = new ArrayList<>();

    private RecyclerView mRecyclerView;
    private MyRecyclerAdapter adapter;

    public FragmentHome() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (container == null) {
            return null;
        }
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);

        mRecyclerView.addItemDecoration(
                new HorizontalDividerItemDecoration.Builder(getActivity())
                        .color(Color.BLACK)
                        .build());

        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(linearLayoutManager);

        updateFeed();

        return view;
    }

    public void updateFeed() {
        showPD();

        adapter = new MyRecyclerAdapter(getActivity(), listItemsList);
        mRecyclerView.setAdapter(adapter);

        RequestQueue request = Volley.newRequestQueue(getActivity());

        adapter.clearAdapter();

        JsonArrayRequest req = new JsonArrayRequest(postsUrl, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());

                try {
                    for (int i = 0; i < response.length(); i++) {
                        JSONObject post = (JSONObject) response.get(i);

                        ListItems item = new ListItems();
                        item.setImage_1(post.getString("image_1"));
                        item.setUsername(post.getString("username"));
                        item.setProfilePicture(post.getString("image_1"));
                        listItemsList.add(item);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
                adapter.notifyDataSetChanged();
                hidePD();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePD();
                Toast.makeText(getActivity(), "Volley Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        request.add(req);
    }

    private void showPD() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("Loading...");
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        }
    }

    private void hidePD() {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePD();
    }

}

关于问题“另外,当我滚动 RecyclerView 时,其中一些会调整为更小或更大的尺寸。" :
顾名思义,“Recycler”,它重用了 ViewHolder 对象。当您向下/向上滚动并且视图(持有者)离开屏幕时,视图对象不会被销毁,但它将再次使用(回收)来保存/表示另一个变得可见的数据集。

如果正在变得可见的新位置处的数据集没有数据(可能为 null 或空等),在您的情况下为 profile_pic/thumbnail,RecyclerView 将使用回收持有者的数据来表示该位置。这就是为什么当您的数据集多于屏幕可以容纳的数据集并且当您向上/向下滚动时,您会看到每次滚动视图(使其可见和不可见)时,它都会根据(回收的)持有者显示不同的数据目前使用。如果您的个人资料图片在每个视图中都与猫的图片不同,那么您可以清楚地见证这种效果。

您要做的是,在将数据(图像、文本等)设置到视图之前,最好先重置它。如果是图像,您可以按照此处的建议清除/重置https://stackoverflow.com/a/8243184/3209739 https://stackoverflow.com/a/8243184/3209739。或者您可以使用占位符图像或使其透明。那么这个问题就不应该出现。
我认为出于同样的原因,它显示了不同尺寸的图像(拇指和个人资料图片)。

在设置实际数据之前尝试重置视图。使用 RecyclerView 时最好遵循这一点。

为什么你想要拥有自己的缓存代码?为什么你不能使用 Picasso 图像加载器、通用图像加载器或适合你的要求的东西。看这里了解不同的图像加载器Picasso vs Imageloader vs Fresco vs Glide https://stackoverflow.com/questions/29363321/picasso-v-s-imageloader-v-s-fresco-vs-glide.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么我的“帖子”在 android recyclerview 中以不同的尺寸加载? 的相关文章

随机推荐