以编程方式添加自定义布局

Programmatically add custom layouts

我有一个卡片布局,可以在多个活动中多次使用。

我的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>

我想将它包含在 activity 中,所以我写了一个 Card class 并添加了更改文本和其他视图值的方法。

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
}  

我正在努力在任何 activity 中渲染这张卡片。我已经在 activity 中创建了 customCard 对象,是否还需要编写其他内容?

您没有将膨胀的视图添加到 CustomCard 中:

见下面的初始化方法:

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

我相信您没有将新创建的卡片附加到 Activity 中的任何布局。

假设您的 activity 的根布局是 ID 为 R.id.activity_mainLinearLayout,那么您可以创建一张新卡片并将其添加到您的 activity与

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

CustomCard card = new CustomCard(this);

layout.addView(card);