【问题标题】:recyclerView can't click itemrecyclerView 无法点击项目
【发布时间】:2017-05-19 04:22:45
【问题描述】:

我无法在我的 recyclerview 上点击一个项目,我认为我的代码很好

主要活动

public class Appetizer extends AppCompatActivity {
    public static final  int CONNECTION_TIMEOUT=10000;
    public static final int READ_TIMEOUT=15000;
    private RecyclerView recyclerView;
    private AdapterFood mAdapter;
    List<DataFood> data=new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appetizer);
        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);

    new AsyncFetch().execute();

   }



   private class AsyncFetch extends AsyncTask<String,String,String>{
       ProgressDialog pdLoading = new ProgressDialog(Appetizer.this);
       HttpURLConnection conn;
       URL url = null;

       @Override
       protected void onPreExecute(){
           super.onPreExecute();

           pdLoading.setMessage("\tLoading...");
           pdLoading.setCancelable(false);
           pdLoading.show();

       }

       @Override
       protected String doInBackground(String... params) {
            try{
                url = new URL("http://kelompokdua.hol.es/private_html/shAppetizer.php");
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return e.toString();
            }

            try {
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                conn.setDoOutput(true);
            }  catch (IOException e1) {
                e1.printStackTrace();
                return e1.toString();
            }
           try {

               int response_code = conn.getResponseCode();

               // Check if successful connection made
               if (response_code == HttpURLConnection.HTTP_OK) {

                   // Read data sent from server
                   InputStream input = conn.getInputStream();
                   BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                   StringBuilder result = new StringBuilder();
                   String line;

                   while ((line = reader.readLine()) != null) {
                       result.append(line);
                   }

                   // Pass data to onPostExecute method
                   return (result.toString());

               } else {

                   return ("unsuccessful");
               }

           } catch (IOException e) {
               e.printStackTrace();
               return e.toString();
           } finally {
               conn.disconnect();
           }


       }


       @Override
       protected void onPostExecute(String result) {

           //this method will be running on UI thread

           pdLoading.dismiss();
           List<DataFood> data=new ArrayList<>();

           pdLoading.dismiss();
           try {

               JSONArray jArray = new JSONArray(result);
               for(int i=0;i<jArray.length();i++){
                   JSONArray innerArray = jArray.getJSONArray(i);
                   for (int j = 0; j < innerArray.length(); j++){
                       JSONObject json_data = innerArray.getJSONObject(j);
//                 JSONArray foodArray= json_data.getJSONArray("");
//                   for (int j=0;j<foodArray.length();j++){
                   DataFood foodData = new DataFood();

                       //JSONObject gambar = json_data.getJSONObject("gambar");
                   foodData.foodImage= json_data.getString("gambar");
                   foodData.foodName= json_data.getString("nama");
                   foodData.foodId= json_data.getInt("id");
                   foodData.price= json_data.getInt("harga");
                   data.add(foodData);
               }}
          // }

               recyclerView = (RecyclerView)findViewById(R.id.lvaptzr);
               LinearLayoutManager layoutManager=new LinearLayoutManager(Appetizer.this);
               recyclerView.setLayoutManager(layoutManager);
               //recyclerView.setLayoutManager(new LinearLayoutManager(Appetizer.this));
               mAdapter = new AdapterFood(Appetizer.this,data);
               recyclerView.setAdapter(mAdapter);


           } catch (JSONException e) {
               Toast.makeText(Appetizer.this,e.toString(),Toast.LENGTH_LONG).show();
               e.printStackTrace();
           }
       }}

}

这是我的适配器

public class AdapterFood extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
    private Context context;
    private LayoutInflater inflater;
    List<DataFood> data = Collections.emptyList();
    DataFood current;
    int currentPos=0;


    public AdapterFood(Context context, List<DataFood> data){
        this.context=context;
        inflater=LayoutInflater.from(context);
        this.data=data;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=inflater.inflate(R.layout.list_item,parent,false);
        Myholder holder=new Myholder(view);
        return holder;

    }


    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        final Myholder myholder=(Myholder) holder;
        DataFood current=data.get(position);
        myholder.textFoodname.setText(current.foodName);
        myholder.textPrice.setText("Rp. " + current.price);
        myholder.textId.setText(String.valueOf(current.foodId));


      // Log.d("IMAGE_URL", "http://kelompokdua.hol.es/pic/" + current.foodImage);
       // Picasso.with(context).load("http://kelompokdua.hol.es/pic/" + current.foodImage).into(myholder.ivFood);
        Glide.with(context).load(current.foodImage).asBitmap()
 //              .placeholder(R.mipmap.ic_launcher).dontAnimate()
//                .error(R.mipmap.minus)
                .into(myholder.ivFood);
    }

    @Override
    public int getItemCount() {

        return data.size();
    }



    class Myholder extends RecyclerView.ViewHolder{
        TextView textFoodname,textPrice,textId;
        ImageView ivFood;

        public Myholder(View view) {
            super(view);
            textFoodname=(TextView) view.findViewById(R.id.textFoodname);
            ivFood=(ImageView)view.findViewById(R.id.ivFood);
            textId=(TextView)view.findViewById(R.id.textid);
            textPrice=(TextView) view.findViewById(R.id.textPrice);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = getAdapterPosition();
                    if (pos != RecyclerView.NO_POSITION){
                        DataFood clickedDataItem = data.get(pos);
                        Intent intent = new Intent(context, Order.class);
                        intent.putExtra("nama", data.get(pos).foodName);
                        intent.putExtra("harga", data.get(pos).price);
                        intent.putExtra("gambar", data.get(pos).foodImage);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                        Toast.makeText(v.getContext(),"clicked" + clickedDataItem.foodName, Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(v.getContext(),"ga",Toast.LENGTH_SHORT).show();

                    }
                }
            });

        }
    }

}

适配器布局

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="390dp"
    android:orientation="vertical">


    <android.support.v7.widget.CardView
        android:id="@+id/cv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:clickable="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clickable="true"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/ivFood"
                android:layout_width="match_parent"
                android:layout_height="320dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:clickable="true"
                android:scaleType="fitXY"
                app:srcCompat="@mipmap/ic_launcher" />

            <TextView
                android:id="@+id/textid"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_toEndOf="@id/ivFood"
                android:layout_toRightOf="@id/ivFood"
                android:clickable="true"
                android:text="id"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="#666" />

            <TextView
                android:id="@+id/textFoodname"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_toLeftOf="@+id/textPrice"
                android:layout_toRightOf="@id/ivFood"
                android:clickable="true"
                android:text="food name"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <TextView
                android:id="@+id/textPrice"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:clickable="true"
                android:text="price"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="@color/colorAccent" />

        </LinearLayout>

    </android.support.v7.widget.CardView>


</RelativeLayout>

MainActivity 布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.kelompok3.restaurantapp.restoranfixx.Isimenu.Appetizer">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/lvaptzr"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:scrollbars="vertical"
        android:visibility="visible" />


</RelativeLayout>

我不知道为什么,我无法单击该项目。当我单击该项目时,甚至连吐司也没有出现。我做错了什么?

【问题讨论】:

  • RecyclerView onClick的可能重复
  • itemView.setOnClickListener... itemView 是从哪里得到的??

标签: android android-recyclerview onclicklistener


【解决方案1】:

试试下面一个

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    final Myholder myholder = (Myholder) holder;
    DataFood current = data.get(position);
    myholder.textFoodname.setText(current.foodName);
    myholder.textPrice.setText("Rp. " + current.price);
    myholder.textId.setText(String.valueOf(current.foodId));

    Glide.with(context).load(current.foodImage).asBitmap()
            .into(myholder.ivFood);

    myholder.cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DataFood clickedDataItem = data.get(position);
            Intent intent = new Intent(context, Order.class);
            intent.putExtra("nama", data.get(position).foodName);
            intent.putExtra("harga", data.get(position).price);
            intent.putExtra("gambar", data.get(position).foodImage);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            Toast.makeText(v.getContext(), "clicked" + clickedDataItem.foodName, Toast.LENGTH_LONG).show();

        }
    });
}

并在 Myholder 类上更新它

class Myholder extends RecyclerView.ViewHolder {
    TextView textFoodname, textPrice, textId;
    ImageView ivFood;
    CardView cardView;

    public Myholder(View view) {
        super(view);
        textFoodname = (TextView) view.findViewById(R.id.textFoodname);
        ivFood = (ImageView) view.findViewById(R.id.ivFood);
        textId = (TextView) view.findViewById(R.id.textid);
        textPrice = (TextView) view.findViewById(R.id.textPrice);
        cardView = (CardView) itemView.findViewById(R.id.cv);
    }
}

【讨论】:

  • 是同一个先生,不能点击
  • 问题是我刚刚在 holder 上调用 onclick 但它应该在 myholder 上
  • 我通过遵循您的代码和@sasikumar 代码解决了这个问题。但结果只是显示图像不是所有内容先生
  • 你是从服务器还是本地获取图像,只是检查一下,因为图像不可能出现在一个上而不会出现在另一个上
  • 来自服务器先生,我认为现在布局是问题
【解决方案2】:

setOnClickListener 应该在 RecyclerView 的 onBindViewHolder 方法中。

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

   myholder.textFoodname.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

                    DataFood clickedDataItem = data.get(position);
                    Intent intent = new Intent(context, Order.class);
                    intent.putExtra("nama", data.get(position).foodName);
                    intent.putExtra("harga", data.get(position).price);
                    intent.putExtra("gambar", data.get(position).foodImage);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                    Toast.makeText(v.getContext(),"clicked" + clickedDataItem.foodName, Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(v.getContext(),"ga",Toast.LENGTH_SHORT).show();

                }

    });

}

【讨论】:

  • 但是,getAdapterPosition();出错了
  • 你可以直接在参数中使用 position..thats (final int position)
  • 怎么样?对不起,我是 android 先生的新手
  • 最终 int pos = 0;像那样?在绑定方法上?
  • @sasikumar 它会抛出编译错误,只是在 psoting 之前查看
【解决方案3】:

您已使 2 个可点击,因此无法点击该项目。

Just remove one clickable from layout which is not using it, keep only the one which used in layout identifer:

 android:clickable="true"

注意:在你的情况下删除所有

【讨论】:

  • 不错的建议,先生
【解决方案4】:

如果你使用recyclerView,你应该尝试“回调接口”;

AdapterFood.class

   public interface OnItemClickLitener {
      void onItemClick(View view, int position);
   }

   private OnItemClickLitener mOnItemClickLitener;

   public void setOnItemClickListener(OnItemClickLitener mOnItemClickLitener) {
    this.mOnItemClickLitener = mOnItemClickLitener;
   }

   @Override
   public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
      itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             mOnItemClickLitener. onItemClick();
        }
   }

我的持有人

  class Myholder extends RecyclerView.ViewHolder {
    TextView textFoodname, textPrice, textId;
    ImageView ivFood;
    CardView cardView;

  public Myholder(View view) {
      super(view);
      textFoodname = (TextView) view.findViewById(R.id.textFoodname);
      ivFood = (ImageView) view.findViewById(R.id.ivFood);
      textId = (TextView) view.findViewById(R.id.textid);
      textPrice = (TextView) view.findViewById(R.id.textPrice);
      cardView = (CardView) itemView.findViewById(R.id.cv);
  }
}

开胃菜

   mAdapter.setOnItemClickListener(new CourseListAdp.OnItemClickLitener() {
     @Override
     public void onItemClick(View view, int position) {
         //your work
         int pos = position;
            if (pos != RecyclerView.NO_POSITION){
          **********
          **********
         }
     }
   }

希望能帮到你

【讨论】:

    【解决方案5】:
    Change Youyr Layout File(remove clickable from yourlayout):
    
          <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dp"
        android:background="#CCC"
        >
    
    
        <android.support.v7.widget.CardView
            android:id="@+id/cv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
    >
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
    
                <ImageView
                    android:layout_gravity="center"
                    android:id="@+id/ivFood"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentStart="true"
                    android:layout_alignParentTop="true"
                    android:scaleType="fitXY"
                    app:srcCompat="@mipmap/ic_launcher" />
    
                <TextView
                    android:id="@+id/textid"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_toEndOf="@id/ivFood"
                    android:layout_toRightOf="@id/ivFood"
                    android:clickable="true"
                    android:text="id"
                    android:textAppearance="?android:attr/textAppearanceSmall"
                    android:textColor="#666" />
    
                <TextView
                    android:id="@+id/textFoodname"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dp"
                    android:layout_toLeftOf="@+id/textPrice"
                    android:layout_toRightOf="@id/ivFood"
                    android:text="food name"
                    android:textAppearance="?android:attr/textAppearanceMedium" />
    
                <TextView
                    android:id="@+id/textPrice"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"
                    android:text="price"
                    android:textAppearance="?android:attr/textAppearanceSmall"
                    android:textColor="@color/colorAccent" />
    
            </LinearLayout>
    
        </android.support.v7.widget.CardView>
    
    
    </LinearLayout>
    
    Change Your Adapter :
    
        public class AdapterFood extends RecyclerView.Adapter<AdapterFood.CustomViewHolder> {
    
    
        private Context context;
        private LayoutInflater inflater;
        List<DataFood> data = Collections.emptyList();
    
    
        public AdapterFood(Context context, List<DataFood> data) {
            this.context = context;
            inflater = LayoutInflater.from(context);
            this.data = data;
        }
    
        @Override
        public AdapterFood.CustomViewHolder onCreateViewHolder(ViewGroup parent, int i) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
            CustomViewHolder viewHolder = new CustomViewHolder(view);
            return viewHolder;
        }
    
        @Override
        public void onBindViewHolder(CustomViewHolder holder, int position) {
    
            DataFood current = data.get(position);
            holder.textFoodname.setText(current.foodName);
            holder.textPrice.setText("Rp. " + current.price);
            holder.textId.setText(String.valueOf(current.foodId));
    
    
            // Log.d("IMAGE_URL", "http://kelompokdua.hol.es/pic/" + current.foodImage);
            Picasso.with(context).load("http://kelompokdua.hol.es/pic/" + current.foodImage).into(myholder.ivFood);
            Glide.with(context).load(current.foodImage).asBitmap()
                    .placeholder(R.mipmap.ic_launcher).dontAnimate()
                    .error(R.mipmap.minus)
                    .into(myholder.ivFood);
    
        }
    
        @Override
        public int getItemCount() {
            return data.size();
        }
    
        public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    
            TextView textFoodname, textPrice, textId;
            ImageView ivFood;
    
    
            public CustomViewHolder(View itemView) {
                super(itemView);
    
                textFoodname = (TextView) itemView.findViewById(R.id.textFoodname);
                ivFood = (ImageView) itemView.findViewById(R.id.ivFood);
                textId = (TextView) itemView.findViewById(R.id.textid);
                textPrice = (TextView) itemView.findViewById(R.id.textPrice);
    
                itemView.setOnClickListener(this);
    
    
            }
    
            @Override
            public void onClick(View v) {
    
    
                Toast.makeText(context, "ga" + getAdapterPosition(), Toast.LENGTH_SHORT).show();
    
    
                int pos = getAdapterPosition();
                if (pos != RecyclerView.NO_POSITION) {
                    DataFood clickedDataItem = data.get(pos);
                    Intent intent = new Intent(context, Order.class);
                    intent.putExtra("nama", data.get(pos).foodName);
                    intent.putExtra("harga", data.get(pos).price);
                    intent.putExtra("gambar", data.get(pos).foodImage);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                    Toast.makeText(v.getContext(), "clicked" + clickedDataItem.foodName, Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(v.getContext(), "ga", Toast.LENGTH_SHORT).show();
    
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多