0

因此,在我的应用程序中,我有一个线性布局,我以编程方式向其中添加了一些 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");
    //...

两张卡片都正确显示,但是显示的第一张卡片在 textViews 中写入了“Title2”和“Description2”,而第二张卡片具有在 xml 中定义的默认值。在我看来,通过调用card.findViewById()orcard2.findViewById()我总是得到第一张卡片的 TextView 。所以我的问题是:我如何设法区分我以编程方式创建的卡片,然后正确访问它们中的视图?

4

1 回答 1

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);
        }
于 2014-09-02T13:04:16.383 回答