我需要设计一个内部有一张或多张卡的布局。问题是卡片的数量在运行时是已知的,我需要每张卡片获得与其他卡片完全相同的高度。因此,如果我有两张卡片,每张卡片的weight
为0.5
当点击一张卡时,此布局应该按下所有其他卡片。
如何实现这一目标?我应该开发自定义视图吗?
更新
我尝试过RecyclerView,我在适配器中添加了以下内容
@Override
public void onBindViewHolder(CardViewHolder holder, int position) {
Card card = cards.get(position);
DisplayMetrics displayMetrics = new DisplayMetrics();
((AppCompatActivity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
holder.tenantId.setText(card.getTenantName());
holder.tenantUsername.setText(card.getUsername());
holder.containerTenant.setBackgroundColor(Color.RED);
holder.tenantLogo.setImageResource(card.getImgResource());
holder.itemView.getLayoutParams().height = (int) (displayMetrics.heightPixels / (cards.size() * 1.0f));
}
但它仍在推动第二张卡,用户需要滚动才能看到第二张卡。
答案 0 :(得分:1)
您应将卡片放入LinearLayout并以编程方式设置重量。
float cardWeight = 1 / numOfCards;
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
cardWeight
);
CARD1.setLayoutParams(param);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
cardWeight
);
CARD2.setLayoutParams(param);
LINEARPARENT.setWeightSum(1f);
LINEARPARENT.addView(CARD1);
LINEARPARENT.addView(CARD2);
关于下推式,您可以将点击的卡片设置为1f(或线性权重)的重量,然后移除其他卡片并在另一个布局上进行充气。
答案 1 :(得分:0)
在玩了@yasin回答之后,我找到了部分解决方案
MainActivity.java
private LinearLayout mLinearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_2);
mLinearLayout = (LinearLayout) findViewById(R.id.ll);
List<Card> cards = new ArrayList<>();
Card c1 = new Card(R.drawable.ic_1, "Username 1", "Tenant 1");
Card c2 = new Card(R.drawable.ic_2, "Username 2", "Tenant 2");
Card c3 = new Card(R.drawable.ic_3, "Username 3", "Tenant 3");
Card c4 = new Card(R.drawable.ic_4, "Username 4", "Tenant 4");
Card c5 = new Card(R.drawable.ic_5, "Username 5", "Tenant 5");
cards.add(c1);
cards.add(c2);
cards.add(c3);
cards.add(c4);
cards.add(c5);
mLinearLayout.setWeightSum(1f);
for (Card c : cards) {
View cardView = getLayoutInflater().inflate(R.layout.tenant_card, null);
TextView tvTenant = (TextView) cardView.findViewById(R.id.tv_tenant);
TextView tvUsername = (TextView) cardView.findViewById(R.id.tv_username);
ImageView imgLogo = (ImageView) cardView.findViewById(R.id.img_logo);
tvTenant.setText(c.getTenantName());
tvUsername.setText(c.getUsername());
imgLogo.setImageResource(c.getImgResource());
float cardWeight = 1 / (cards.size() * 1.0f);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
0,
cardWeight
);
cardView.setLayoutParams(param);
mLinearLayout.addView(cardView);
}
}