2017-03-01 83 views
0

我有一個可在多個活動中多次使用的卡布局。以編程方式添加自定義佈局

我custom_card.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:card_view="http://schemas.android.com/apk/res-auto" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:background="#000000"> 

<android.support.v7.widget.CardView 
    android:id="@+id/card_view" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    card_view:cardCornerRadius="4dp" 
    card_view:contentPadding="10dp" 
    tools:padding="15dp"> 

     </android.support.v7.widget.CardView> 
</RelativeLayout> 

我想包括這一個活動,所以我寫了一個卡類,並添加方法來改變文本和其他視圖值。

CustomCard.java

public class CustomCard extends RelativeLayout{ 

    private Context mContext; 
    private LayoutInflater layoutInflater; 
    private View mView; 
    private ImageView mCardImg; 
    private TextView mCardTitle; 
    private TextView mCardDescription; 

    public CustomCard(Context context){ 
     super(context); 
     mContext = context; 
     init(); 
    } 

    public void init(){ 
     layoutInflater = (LayoutInflater) mContext 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     mView = layoutInflater.inflate(R.layout.custom_card, this, true); 

    } 

    // setters of texts and other view elements 
} 

我與任何活動中渲染此卡掙扎。我在活動內部創建了customCard對象,是否還需要編寫其他內容?

+0

你動態地創建這個CustomCard或使用XML添加到您的活動? –

+0

我動態創建使用佈局的CustomCard對象 –

回答

0

我相信你不重視新創建的卡到任何您在活動的佈局。

比方說,你的活動將根佈局是LinearLayout用id R.id.activity_main,那麼你就可以創建一個新卡,並將其與

LinearLayout layout = (LinearLayout) findViewById(R.id.activity_main); 

CustomCard card = new CustomCard(this); 

layout.addView(card); 
+1

是的,它解決了這個問題。謝謝 –

+0

我試圖通過 爲(int i = 0; i <10; i ++)添加多個卡CustomCard card = new CustomCard(getApplicationContext()); mCurrentLayout.addView(card); } 但它只創建一張卡片 –

+0

也許你只在UI上看到一張卡片,因爲你的卡片的寬度和高度均爲'match_parent',在這種情況下,這可能是整個活動佈局的大小。嘗試使用'wrap_content'或固定大小來代替高度和寬度。 – zsmb13

0

您沒有添加您的充氣視圖到CustomCard:

見下文init方法:

public void init(){ 
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
mView = layoutInflater.inflate(R.layout.dwsdf, this, true); 
//Add below line into your code 
addView(mView); 
} 
+0

它創建與此異常的崩潰 android.os.TransactionTooLargeException:數據包大小16110580字節 –

+0

發佈您的Java代碼,您已創建Customlayout。 –

+0

通過在最後一個膨脹方法參數中傳遞false來嘗試。 –

相關問題