所以在我的应用程序中我有一个线性布局,我以编程方式添加一些CardViews(android L cardview),如下所示:
//This is my LinearLayout
LinearLayout myLayout = (LinearLayout) findViewById(R.id.accounts_layout);
//Here i create my CardView from a prepared xml layout and inflate it to the LinearLayout
View card = View.inflate(getApplicationContext(), R.layout.account_card, myLayout);
//Now i change the 'text' value of the Card's text views
TextView cardTitle = (TextView) card.findViewById(R.id.text_card_title);
cardTitle.setText("Title1");
TextView cardDecription = (TextView) card.findViewById(R.id.text_card_description);
cardDecription.setText("Description1");
//...
//Now i do the same thing for another card
View card2 = View.inflate(getApplicationContext(), R.layout.account_card, myLayout);
TextView cardTitle2 = (TextView) card2.findViewById(R.id.text_card_title);
cardTitle2.setText("Title2");
TextView cardDecription2 = (TextView) card2.findViewById(R.id.text_card_description);
cardDecription2.setText("Description2");
//...
这两张牌显示得很好,但会发生的事情比显示的第一张牌有" Title2"和"描述2"写在textViews中,而第二张卡具有xml中定义的默认值。
在我看来,通过调用card.findViewById()
或card2.findViewById()
,我总是得到第一张卡片的TextView。
所以我的问题是:我如何设法区分我以编程方式创建的卡片然后相关地访问其中的视图?
答案 0 :(得分:2)
请尝试这种方式,希望这有助于您解决问题。
LinearLayout myLayout = (LinearLayout) findViewById(R.id.accounts_layout);
for (int i=1;i<=2;i++){
View card = View.inflate(getApplicationContext(), R.layout.account_card, null);
TextView cardTitle = (TextView) card.findViewById(R.id.text_card_title);
cardTitle.setText("Title"+i);
TextView cardDecription = (TextView) card.findViewById(R.id.text_card_description);
cardDecription.setText("Description"+i);
card.setTag(i);
card.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = (Integer) v.getTag();
Toast.makeText(context,pos,Toast.LENGTH_SHORT).show();
}
});
myLayout.addView(card);
}