【问题标题】:How to dynamically add cardview to grid layout如何将cardview动态添加到网格布局
【发布时间】:2023-03-14 19:58:02
【问题描述】:

我正在尝试将 cardview 动态添加到 GridLayout。但它没有添加卡片视图。

层次结构是 ScrollView --> Horizo​​ntalScrollView --> LinearLayout --> GridLayout,我想添加到这个网格布局中。我的代码是:

public class MainActivity extends AppCompatActivity {
GridLayout gridLayout;
TextView tc;
CardView newc;
@SuppressLint("SetTextI18n")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    gridLayout = findViewById(R.id.gridlayout);

   newc = new CardView(getApplicationContext());
   newc.setLayoutParams(new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
   newc.setRadius(8);
   newc.setCardElevation(10);
   tc = new TextView(getApplicationContext());
   tc.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
   tc.setText("This is dynamic");
   newc.addView(tc);
   GridLayout.Spec row = GridLayout.spec(0);
   GridLayout.Spec col = GridLayout.spec(0);
   GridLayout.LayoutParams gridP = new GridLayout.LayoutParams(row, col);
   gridLayout.addView(newc, gridP);

}
}

那么如何将视图动态添加到 GridLayout。

谢谢。

【问题讨论】:

    标签: android android-layout grid-layout


    【解决方案1】:

    你的代码中有一些错误......使用这个

    newc = new CardView(getApplicationContext());
    newc.setLayoutParams(new CardView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    newc.setRadius(8);
     newc.setCardElevation(10);
    tc = new TextView(getApplicationContext());
    tc.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    tc.setText("This is dynamic");
    newc.addView(tc);
    gridLayout.setColumnCount(2);
    gridLayout.setOrientation(GridLayout.HORIZONTAL);
    gridLayout.addView(newc);
    

    如果你想为特定的行和特定的列添加视图,请使用这个

     GridLayout.Spec row = GridLayout.spec(0); // Mention row index here
       GridLayout.Spec col = GridLayout.spec(0);// Mention column index here
       GridLayout.LayoutParams gridP = new GridLayout.LayoutParams(row, col);
    

    在您的情况下,您始终使用 0,0 表示行和列,因此基本上发生的情况是视图被添加到网格布局中,但它们是重叠的,因此您无法看到这些

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多