我正在使用CardView佈局作爲RecyclerView的行。不過,我在將OnClickListener附加到佈局時遇到了問題。 我使用以下佈局RecyclerView中CardView和OnClickListener問題
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="@dimen/unit_5"
android:clickable="true"
android:longClickable="true"
card_view:cardCornerRadius="@dimen/unit_5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="@dimen/spinnerWidth"
android:background="@drawable/row_item_background"
android:clickable="true"
android:orientation="vertical"
android:padding="@dimen/dialog_left_padding">
<!-- Other items -->
</LinearLayout>
</android.support.v7.widget.CardView>
以下是我的適配器和ViewHolder
private class SampleAdapter extends RecyclerView.Adapter<SampleViewHolder> {
ArrayList<Item> arrayList;
private LayoutInflater inflater;
public SampleAdapter(Context context) {
inflater = LayoutInflater.from(context);
this.arrayList = new ArrayList<>();
arrayList.addAll(items);
}
@Override
public SampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.layout1, parent, false);
SampleViewHolder holder = new SampleViewHolder(view);
holder.setClickHandler(handler);
return holder;
}
@Override
public void onBindViewHolder(SampleViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return arrayList.size();
}
}
static class SampleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
TextView name;
IClickHandler clickHandler;
public IClickHandler getClickHandler() {
return clickHandler;
}
public void setClickHandler(IClickHandler clickHandler) {
this.clickHandler = clickHandler;
}
public SampleViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView
.findViewById(R.id.name);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
@Override
public void onClick(View view) {
if (getClickHandler() != null) {
getClickHandler().onItemClicked(view, getLayoutPosition());
}
}
@Override
public boolean onLongClick(View view) {
if (getClickHandler() != null) {
getClickHandler().onItemLongClicked(view, getLayoutPosition());
}
return true;
}
}
但這onClick函數永遠不會被解僱。
但是,如果我用LinearLayout替換CardView,每件事情都可以正常工作。 我不知道這裏有什麼問題。有人可以幫助我嗎?
謝謝。
發佈完整的適配器和用於初始化recyclerView的代碼和聽衆的設置。 – theapache64
添加了代碼。 –
對不起,這是我的知識。 – theapache64