当前位置: 首页 > 知识库问答 >
问题:

RecyclerView仅显示一个项目

姜明贤
2023-03-14
     <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.aleky.carrental.cars">
    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >
    <android.support.v7.widget.RecyclerView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/rv"
        android:clickable="false"
        />
        </RelativeLayout>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:cardview="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp"
    cardview:cardCornerRadius="2dp"
    cardview:cardElevation="3dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"
        android:paddingBottom="15dp">

        <TextView
            android:id="@+id/car_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dp"
            android:layout_marginTop="2dp"
            android:fontFamily="sans-serif-smallcaps"
            android:text="Car Name"
            android:textColor="#996515"
            android:textSize="24sp"
            android:textStyle="bold" />

        <com.android.volley.toolbox.NetworkImageView
            android:id="@+id/Car_image"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_below="@+id/car_name"
            android:layout_marginBottom="2dp"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="2dp" />

        <TextView
            android:id="@+id/tvfeature"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="90dp"
            android:layout_marginTop="25dp"
            android:layout_toRightOf="@+id/car_name"
            android:text="Features"
            android:textColor="#000"
            android:textSize="22sp" />

        <View
            android:layout_width="100dp"
            android:layout_height="1dp"
            android:layout_below="@+id/tvfeature"
            android:layout_marginLeft="20dp"
            android:layout_toRightOf="@+id/Car_image"
            android:background="#000" />

        <ImageView
            android:id="@+id/ac"
            android:layout_width="40dp"
            android:layout_height="20dp"
            android:layout_below="@+id/tvfeature"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="10dp"
            android:layout_toRightOf="@+id/Car_image"
            android:src="@drawable/air_conditioner" />

        <TextView
            android:id="@+id/feature1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/tvfeature"
            android:layout_marginTop="10dp"
            android:layout_toRightOf="@+id/ac"
            android:text="Air conditioner"
            android:textColor="#000"
            android:textSize="16sp" />

        <ImageView
            android:id="@+id/tr"
            android:layout_width="40dp"
            android:layout_height="20dp"
            android:layout_below="@+id/feature1"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="10dp"
            android:layout_toRightOf="@+id/Car_image"
            android:src="@drawable/transmission" />

        <TextView
            android:id="@+id/feature2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/feature1"
            android:layout_marginLeft="2dp"
            android:layout_marginTop="10dp"
            android:layout_toRightOf="@+id/tr"
            android:text="Manual"
            android:textColor="#333333"
            android:textSize="16sp" />

        <ImageView
            android:id="@+id/pass"
            android:layout_width="40dp"
            android:layout_height="20dp"
            android:layout_below="@+id/tr"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="5dp"
            android:layout_toRightOf="@+id/Car_image"
            android:src="@drawable/passengers" />

        <TextView
            android:id="@+id/feature3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/feature2"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="5dp"
            android:layout_toRightOf="@id/pass"
            android:text="6 Passengers"
            android:textColor="#333333"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/pricetxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/Car_image"
            android:text="Price :"
            android:textColor="#333333"
            android:textSize="22sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/car_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/Car_image"
            android:layout_marginLeft="2dp"
            android:layout_toRightOf="@+id/pricetxt"
            android:text="KSH.2000"
            android:textColor="#996515"
            android:textSize="22sp" />

        <TextView
            android:id="@+id/organiser"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/pricetxt"
            android:layout_marginTop="5dp"
            android:text="Owner :"
            android:textColor="#333333"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/crAgent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/pricetxt"
            android:layout_marginLeft="2dp"
            android:layout_marginTop="5dp"
            android:layout_toEndOf="@+id/organiser"
            android:layout_toRightOf="@+id/organiser"
            android:text="Supercars Rentals"
            android:textColor="#05056c"
            android:textSize="14sp" />

        <Button
            android:id="@+id/btn_rent"
            style="@style/AppTheme.ButtonCorners"
            android:layout_width="150dp"
            android:layout_height="40dp"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/Car_image"
            android:layout_marginRight="12dp"
            android:clickable="true"
            android:text="Rent"
            android:textColor="#eef525" />

        <TextView
            android:id="@+id/car_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="invisible" />
    </RelativeLayout>
</android.support.v7.widget.CardView>
   public class cars extends AppCompatActivity {
    String url = "http://192.168.43.201/Car_rental/retrievecars.php";
    Context context = null;
    ProgressDialog dialog;
    private List<CarsItem> array_cars = new ArrayList<>();
    AdapterClass adapter;
    NetworkImageView carsImageview;
    private String user_Location = "cLocation";
    private String Category = "category";


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

        setContentView(R.layout.activity_cars);
        adapter = new AdapterClass(cars.this, array_cars);
        RecyclerView recycler = (RecyclerView) findViewById(R.id.rv);
        recycler.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycler.setLayoutManager(layoutManager);
        recycler.setItemAnimator(new DefaultItemAnimator());
        recycler.setAdapter(adapter);
        setCars();
        recycler.addOnItemTouchListener(new RecyclerTouchListener(this, recycler, new ClickListener() {

            @Override
            public void onClick(View view, int position) {


            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));


    }

    public void setCars() {
        dialog = new ProgressDialog(this);
        dialog.setMessage("Loading cars...");
        dialog.show();

        if (array_cars != null) {
            array_cars.clear();
        }
        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        try {
                            hideDialog();
                            Log.d("Sever Message", s);

                            JSONObject cars = new JSONObject(s);

                            JSONArray jsonArray = cars.getJSONArray("Cars");
                            JSONObject jobject = null;
                            int len = jsonArray.length();

                            for (int i = 0; i < len; i++) {

                                jobject = jsonArray.getJSONObject(i);
                                CarsItem carsdata = new CarsItem();
                                carsdata.setId(jobject.getString("0"));
                                carsdata.setCarname(jobject.getString("1"));
                                carsdata.setImages(jobject.getString("car_image"));
                                carsdata.setfeature1(jobject.getString("5"));

                                carsdata.setfeature2(jobject.getString("6"));
                                carsdata.setfeature3(jobject.getString("7"));
                                carsdata.setPrice(jobject.getString("8"));
                                array_cars.add(carsdata);
                            }

                            adapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                //Getting Image Location & category
                String Location = "";
                String Ccategory = "cars";

                //Creating parameters
                Map<String, String> params = new Hashtable<String, String>();

                //Adding parameters
                params.put(Category, Ccategory);
                params.put(user_Location, Location);

                //returning parameters
                return params;
            }
        };
        //RequestQueue requestQueue = Volley.newRequestQueue(this);
        //Adding our request to the queue
        // requestQueue.add(request);
        AppController.getmInstance().addToRequestQueue(request);
    }

    public void hideDialog() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    public interface ClickListener {
        void onClick(View view, int position);

        void onLongClick(View view, int position);
    }

    public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        GestureDetector gestureDetector;
        cars.ClickListener clickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final cars.ClickListener clickListener) {
            this.clickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null) {
                        clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView recycler, MotionEvent e) {

            View child = recycler.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
                clickListener.onClick(child, recycler.getChildPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView recycler, MotionEvent e) {
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }

    }

}

最后是我的适配器类

    public class AdapterClass extends RecyclerView.Adapter<AdapterClass.CustomViewHolder> {
    private List<CarsItem> Array_cars;
    private ImageLoader imageLoader;
    private Context mContext;


    public AdapterClass(Context context, List<CarsItem> array_cars) {
        this.Array_cars = array_cars;
        this.mContext = context;
    }



    @Override
    public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cars_design, null);

        return new CustomViewHolder(view);
    }

    @Override
    public void onBindViewHolder(CustomViewHolder holder,final int i) {
        final CarsItem carsItem = Array_cars.get(i);
        holder.imageUrl = carsItem.getImages();

        imageLoader = AppController.getmInstance().getmImageLoader();
        holder.Carname.setText(carsItem.getCarname());
        holder.feature1.setText(carsItem.getfeature1());
        holder.feature2.setText(carsItem.getfeature2());
        holder.feature3.setText(carsItem.getfeature3());
        holder.price.setText(carsItem.getPrice());
        holder.agent.setText(carsItem.getcarowner());
        holder.carid.setText(carsItem.getId());
        holder.carimage.setImageUrl("http://192.168.43.201/Car_rental/cars/"+carsItem.getImages(), imageLoader);

        holder.rent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, HireCar.class);

                intent.putExtra("carname",carsItem.getCarname());
                intent.putExtra("car_rate",carsItem.getPrice());
                intent.putExtra("car_image", carsItem.getImages());
                intent.putExtra("car_id", carsItem.getId());
                intent.putExtra("c_owner", carsItem.getcarowner());

                mContext.startActivity(intent);

            }
        });

    }

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

    class CustomViewHolder extends RecyclerView.ViewHolder  {
        String imageUrl;
        TextView Carname, feature1, feature2, feature3, price,agent,carid;
        NetworkImageView carimage;
        Button rent;

        public CustomViewHolder(View view) {
            super(view);
            this.Carname = (TextView) view.findViewById(R.id.car_name);
            this.feature1 = (TextView) view.findViewById(R.id.feature1);
            this.feature3 = (TextView) view.findViewById(R.id.feature3);
            this.price = (TextView) view.findViewById(R.id.car_price);
            this.feature2=(TextView) view.findViewById(R.id.feature2);
            this.carimage = (NetworkImageView) view.findViewById(R.id.Car_image);
            this.rent=(Button)view.findViewById(R.id.btn_rent);
            this.agent=(TextView)view.findViewById(R.id.crAgent);
            this.carid=(TextView)view.findViewById(R.id.car_id);

        }


    }
}

共有1个答案

蒋嘉颖
2023-03-14

我认为问题是您没有将元素添加到适配器中。您需要在适配器中有一个方法,以便在适配器创建后添加项。在该方法中,您需要通知。示例:

void addItems(List<CarItem> carItems){
   Array_cars.addAll(carItems);
   notifyDataSetChanged();
}

然而,我会走得更远一点,找到项目的数量,并尝试只通知新插入的项目(以防已经有一些项目)。可以这样做:

void addItems(List<CarItem> carItems){
    int position = Array_cars.size();
    Array_cars.addAll(carItems);
    notifyItemRangeChanged(position, Array_cars.size() - position);
}

编辑

 类似资料:
  • 问题就在这里:我创建了世界上最简单的RecyclerView,但它只显示第一个项目。我不明白为什么。谢谢你的帮助。 item_layout.xml mainactivity.java

  • 我试图在一个对话框中的recyclerView中显示数据,数据是从HTTP请求获取的。 我验证了适配器是否获得了数据——我在适配器中打印了数组长度,结果很好,但由于某些原因它不会显示数据——我所能看到的只是一个空白区域,recyclerView应该在那里。 重要提示:该应用程序运行良好,运行时没有错误或其他问题,回收器视图不存在。 xmi文件:

  • 这是我现在面临的一个奇怪的问题。从我的应用程序中,我从JSON文件中从链接中获取数据,然后用Volley解析它。现在我想在一个看起来不起作用的RecyclerView上显示数据,我很高兴我的代码很好,但是有些东西似乎不起作用,我找不到它。 这是活动代码 HomeActivity.java: 这是我从适配器中扩展的布局,并从JSON文件中设置数据 和适配器类相关的代码,我猜: @Override p

  • 问题内容: 我正在尝试将数据库项目显示为,这是我的代码。 我确实宣布并 该方法/功能将被调用,然后用户按下登录按钮。 我现在遇到的问题是,它仅显示一项,而我的数据库有多项。 有人知道为什么吗? 问题答案: 将您从数据库中获得的数据存储在矢量对象中,完成后将矢量对象在组合框中设置为新模型。试试这个, 不要 在 循环 内 关闭连接。

  • 我正在PyGame中制作一个太空入侵者游戏,但当我尝试绘制投射物时,它会覆盖/更改主精灵(平面)。如何解决此问题,以便在屏幕上显示多个精灵?

  • 如何使用网格布局管理器水平显示三行三列的循环视图项目,增加垂直增加的价值,类似于下图