首页 > 解决方案 > 如何仅使用 Java (android studio) 创建具有特定布局的卡片视图

问题描述

我正在制作一个类似于 facebook 的应用程序,其中我有一个显示所有帖子的新闻提要。但是,此提要中的帖子数量因每个用户而异,具体取决于他们拥有的朋友数量和发布的帖子数量。我想为每个帖子项目创建一个 CardView,它将显示发布它的用户的姓名、发布时间和实际帖子本身。布局将水平拆分一次,下半部分是帖子,上半部分是人名和发布时间。

目前我只能通过更改 xml 文本找到方法来做到这一点,但我想在需要时在我的 Java 代码中创建这些 CardView。

我知道我可以通过使用setText() & setTextSize() 之类的函数来更改 TextViews。有没有办法让我在可以改变基本布局的 CardView 上使用类似的功能。

for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

   CardView TVcard = new CardView(Home.this);

   TextView TVposts = new TextView(Home.this);
   TextView test = new TextView(Home.this);

   TVcard.addView(TVposts);
   TVcard.addView(test);

   test.setText("test");
   test.setBackgroundColor(Color.GREEN);


   TVposts.setText(snapshot.getValue().toString());
   TVposts.setTextColor(Color.WHITE);
   TVposts.setTextSize(25);
   TVposts.setBackgroundColor(Color.BLACK);
   TVposts.setHeight(200);

   linearLayout.addView(TVcard);
   LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) TVcard.getLayoutParams();
   params.setMargins(0, 20, 0, 0);
   TVcard.setLayoutParams(params);
}

谢谢

标签: javaxmlandroid-cardviewcardview

解决方案


推荐阅读