Murali Krish Murali Krish - 1 year ago 92
Android Question

How to Create CardView programtically with two text views aligned vertically in it?

Created a CardView instance and attached LinearLayout.LayoutParams, then added two TextViews to CardView, but TextViews overlap over each other instead of aligning one below the another

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);

card.setLayoutParams(params);
int margin = 10;
params.setMargins(margin, margin, margin, margin);
// Set CardView corner radius
card.setRadius(15);
// Set cardView content padding
card.setContentPadding(20, 20, 20, 20);
// Set a background color for CardView
card.setCardBackgroundColor(Color.parseColor("#FFC6D6C3"));
// Set the CardView maximum elevation
card.setMaxCardElevation(15);
// Set CardView elevation
card.setCardElevation(9);

// Initialize a new TextView to put in CardView
TextView tv = new TextView(mContext);
tv.setText(title);
tv.setTypeface(null, Typeface.BOLD);
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
tv.setTextColor(Color.parseColor("#006699"));


// Put the TextView in CardView
card.addView(tv);

TextView tv1 = new TextView(mContext);
tv1.setText(title);
tv1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);
tv1.setTextColor(Color.parseColor("#006699"));

card.addView(tv1);
// Finally, add the CardView in root layout
rl.addView(card);

Answer Source

To achieve what you want, you need to create an object LinearLayout that will contain your TextViews and then add that LinearLayout to the CardView object

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download