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

时间:2017-03-01 09:54:56

标签: java android android-custom-view

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

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

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

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的对象,是否还需要编写其他内容?

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

我相信您并未将新创建的卡片附加到活动中的任何布局中。

假设您的活动的根布局为LinearLayout且ID为R.id.activity_main,那么您可以创建一张新卡并将其添加到您的活动中

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

CustomCard card = new CustomCard(this);

layout.addView(card);