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");
    //...

2 つのカードは正しく表示されますが、表示される最初のカードには textViews に「Title2」と「Description2」が書き込まれ、2 番目のカードには xml で定義されたデフォルト値が含まれます。card.findViewById()呼び出すかcard2.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 に答える