如何使用垂直对齐的两个文本视图以编程方式创建 CardView?
How to Create CardView programmatically with two text views aligned vertically in it?
创建了一个 CardView 实例并附加了 LinearLayout.LayoutParams,然后向 CardView 添加了两个 TextView,但 TextView 彼此重叠,而不是一个在另一个下面对齐
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);
要实现您想要的效果,您需要创建一个包含您的 TextView
的对象 LinearLayout
,然后将 LinearLayout
添加到 CardView
对象
创建了一个 CardView 实例并附加了 LinearLayout.LayoutParams,然后向 CardView 添加了两个 TextView,但 TextView 彼此重叠,而不是一个在另一个下面对齐
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);
要实现您想要的效果,您需要创建一个包含您的 TextView
的对象 LinearLayout
,然后将 LinearLayout
添加到 CardView
对象