2014-09-02 55 views
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"); 
    //... 

兩個卡都正確顯示,但是會發生的情況是,顯示的第一張牌具有寫在textView中的「Title2」和「Description2」,而第二張牌具有在xml中定義的默認值。 在我看來,通過調用card.findViewById()card2.findViewById()我總是得到第一張卡的TextView。 所以我的問題是:我如何設法區分我以編程方式創建的卡片,然後通過它們訪問其中的視圖?

回答

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); 
     } 
+0

感謝它的方式!但另一個問題出現了:我在xml中放置了一些標題屬性(高度,寬度,邊界,ecc ..),但現在這些屬性不再被考慮! – Fiora 2014-09-02 13:18:21