我是Android开发人员的新手,我在尝试以编程方式设置it.gmariotti.cardslib.library.view.CardView
的最小高度时遇到问题。我创建了一个CardView的新实例,并在代码中设置了所有xml元素,但它不会影响cardView。我不会从xml中充实cardview。
CardView catCard = new CardView(getActivity());
catCard.setBackgroundColor(Color.green(0));
catCard.setMinimumHeight(10);
catCard.setBottom(0);
catCard.setExpanded(false);
答案 0 :(得分:7)
CardView扩展了FrameLayout,因此您应该能够设置LayoutParams。尝试这样的事情:
CardView.LayoutParams layoutParams = (CardView.LayoutParams)
catCard.getLayoutParams();
layoutParams.height = 10;
,不要忘记设置Width也是必需的。 或者像这样创建新的LayoutParams(未经测试):
CardView catCard = new CardView(getApplicationContext());
// sets width to wrap content and height to 10 dp ->
catCard.setLayoutParams(new CardView.LayoutParams(
CardView.LayoutParams.WRAP_CONTENT, 10));
catCard.setMinimumHeight(10);
答案 1 :(得分:5)
myCardView.setLayoutParams(new RelativeLayout.LayoutParams(20, 20));
这取决于您的cardview是哪个布局的子项,在这种情况下,它位于相对布局
下答案 2 :(得分:0)
我的解决方案有保证金,并且对我来说效果很好
val resources = context.resources // get resources from context
val width: Int = resources.displayMetrics.widthPixels / 3 //get width
val px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2f, resources.displayMetrics).toInt() //set margin
val layoutParams = ViewGroup.MarginLayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT)
layoutParams.marginStart = px
layoutParams.marginEnd = px
cardView.layoutParams = layoutParams