我有一個CustomersAdapter
類爲我的RecyclerView
,我嘗試在RecyclerView行上實現onclick事件。但不幸的是,它不適合我。Recycler View Onclick android不工作
public class CustomersAdapter extends RecyclerView.Adapter<CustomersAdapter.MyViewHolder> {
private List<Customers> customerList;
Context ctx;
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.customers_layout, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Customers customer = customerList.get(position);
holder.customerName.setText(customer.getCustomerName());
}
@Override
public int getItemCount() {
return customerList.size();
}
public CustomersAdapter(List<Customers> customerList,Context ctx) {
this.customerList = customerList;
this.ctx = ctx;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView customerName;
public MyViewHolder(View view) {
super(view);
customerName = (TextView) view.findViewById(R.id.cust_name);
}
@Override
public void onClick(View v) {
int position = getAdapterPosition(); // gets item position
if (position != RecyclerView.NO_POSITION) {
Customers customer= customerList.get(position);
Toast.makeText(ctx, customer.getCustomerName(), Toast.LENGTH_SHORT).show();
}
}
}
}
XML:customers_layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:clickable="true"
>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
>
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:id="@+id/cust_img"
android:src="@drawable/person"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/cust_name"
android:textColor="#000"
android:text="HELLO"
android:layout_marginLeft="13dp"
android:layout_marginStart="13dp"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/cust_img"
android:layout_toEndOf="@+id/cust_img" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
是否有任何錯誤或狀態? – mcemilg
沒有應用程序運行過程中出現罰款我試着調試應用程序,但它不是進入的onclick方法 –