[英]Set onClickListener on the RelativeLayout contained by CardView
我想設置onClickListener
每個我的CardView
元素。 由於我無法在卡本身上設置onClickListener
(請參見此處 ),因此我考慮將其設置為卡所包含的RelativeLayout。 現在,我正在使用本機CardView庫並應用了本教程。
這是我的MainActivity
的onCreate
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recycleCardView = (RecyclerView) findViewById(R.id.cardList);
recycleCardView.setHasFixedSize(true);
LinearLayoutManager llmanager = new LinearLayoutManager(this);
llmanager.setOrientation(LinearLayoutManager.VERTICAL);
recycleCardView.setLayoutManager(llmanager);
data = createList(9);
ContactAdapter ctadapter = new ContactAdapter(data);
//...
recycleCardView.setAdapter(ctadapter);
這是item_card_view
xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/card_view"
android:layout_width="match_parent" android:layout_height="match_parent"
card_view:cardCornerRadius="4dp"
android:layout_margin="5dp">
<RelativeLayout android:id="@+id/nativecardlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:background="?android:selectableItemBackground">
<!--some more layout-->
</RelativeLayout>
</android.support.v7.widget.CardView>
這是我的ContactAdapter
的onCreateViewHolder
:
@Override
public ContactViewHolder onCreateViewHolder(final ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_card_view, viewGroup, false);
RelativeLayout cardlayout = (RelativeLayout)
viewGroup.findViewById(R.id.nativecardlayout); //NullPointerException here
cardlayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(viewGroup.getContext(), "Clickable card", Toast.LENGTH_LONG).show();
}
});
return new ContactViewHolder(itemView);
}
我的問題是,我要加載的RelativeLayout位於cardview
元素內,為null。 因此,我得到了NullPointerException
。
如何在每個RelativeLayout上設置onClickListener
? 這可能嗎?
參見下面的編輯,其邏輯錯誤:
RelativeLayout cardlayout = (RelativeLayout)itemView.findViewById(R.id.nativecardlayout);
您可以將偵聽器設置為所有視圖。 因此,這是可能的。
取代這個
RelativeLayout cardlayout = (RelativeLayout)
viewGroup.findViewById(R.id.nativecardlayout);
有了這個
RelativeLayout cardlayout = (RelativeLayout)
itemView.findViewById(R.id.nativecardlayout);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.