我的主要活动有imageview,我想在点击它时创建一张新卡,我想管理它们。点击图片查看时如何添加卡片布局。这是我的cardview布局xml card_view.xml
<android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/cv" > <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" > <TextView android:layout_width="300dp" android:layout_height="150dp" android:text="I'm here" android:id="@+id/textView" /> </RelativeLayout> </android.support.v7.widget.CardView> </LinearLayout>
卡片类只持有一个字符串
public class Card {
String information;
public void setInformation(String info)
{
information=info;
}
public String getInformation()
{
return information;
}
这是我的适配器
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private LayoutInflater inflater;
private List<Card> cards;
public MyAdapter (Context context,List<Card> cards)
{
inflater=LayoutInflater.from(context);
this.cards=cards;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= inflater.inflate(R.layout.card_view,parent,false);
MyViewHolder holder=new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.textview.setText(cards.get(position).information);
}
@Override
public int getItemCount() {
return cards.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder
{
TextView textview;
CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
textview=(TextView)itemView.findViewById(R.id.textView);
cardView=(CardView)itemView.findViewById(R.id.cv);
}
}
和主要
private MyAdapter adapter;
private List<Card> cards=new ArrayList<>();
private RecyclerView rv;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rv = (RecyclerView)findViewById(R.id.rv);
rv.setHasFixedSize(true);
final LinearLayoutManager llm=new LinearLayoutManager(getApplicationContext());
rv.setLayoutManager(llm);
final Card current=new Card();
adapter=new MyAdapter(this,cards);
rv.setAdapter(adapter);
iView=(ImageView)findViewById(R.id.imageView);
iView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
current.information="Hello";
cards.add(current);
//mLayout.addView();
}
});
答案 0 :(得分:0)
当您更改在ListView
或RecyclerView
中使用的适配器的underling数据集时,必须调用适配器的notifyDataSetChanged()
才能使更改生效。
因此,在代码中,您可以使用onClick()
方法将卡片添加到卡片组中,然后调用notifyDataSetChanged()
。
所以改变这个:
public void onClick(View v) {
current.information="Hello";
cards.add(current);
//mLayout.addView();
}
}
到此:
public void onClick(View v) {
current.information="Hello";
cards.add(current);
adapter.notifyDataSetChanged();
//mLayout.addView();
}
}