Android Java以编程方式在gridlayout内部创建线性布局

时间:2018-07-26 07:38:14

标签: java android cardview

我正在尝试通过API在网格布局内创建cardview或linearlayout,因此我尝试使用Java而不是xml来创建它。

我几乎无法实现我想要的功能,但是当布局中的文本视图过长时,布局就会损坏,

这是短文字时的屏幕截图

enter image description here

这是文本太长的时候

enter image description here

这是我的代码

ViewGroup.LayoutParams params = new LinearLayout
    .LayoutParams(GridLayout.LayoutParams.MATCH_PARENT, GridLayout.LayoutParams.WRAP_CONTENT);
grid = v.findViewById(R.id.div_kategori);
grid.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
//grid.setLayoutParams(params);
grid.setColumnCount(3);
//grid.setRowCount(5);

int row = 1;
int col = 1;

for (int i=0; i<user.length(); i++) {
    JSONObject obj = user.getJSONObject(i);
    String nama_kategori = obj.getString("nama_kategori");

    if(i>0){
        if(i%3==0){
            row++;
            col = 1;
        }
    }

    Log.d("nama_kategori",nama_kategori+" baris : "+row+" kolom : "+col);

    LinearLayout card = new LinearLayout(getContext());
    GridLayout.LayoutParams param = new GridLayout
        .LayoutParams(GridLayout.spec(GridLayout.UNDEFINED, 1f),      GridLayout.spec(GridLayout.UNDEFINED, 1f));
    card.setPadding(10,10,10,10);
    card.setBackgroundColor(Color.RED);
    card.setLayoutParams(param);

    FrameLayout frame = new FrameLayout(getContext());
    ViewGroup.LayoutParams paramframe = new LinearLayout
        .LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
    frame.setLayoutParams(paramframe);
    frame.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.card_edge) );

    LinearLayout lin = new LinearLayout(getContext());
    LinearLayout.LayoutParams paramlin = new LinearLayout
        .LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
    paramlin.setMargins(10,10,10,10);
    lin.setBackgroundColor(Color.BLUE);
    lin.setLayoutParams(paramlin);
    lin.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(getContext());
    tv.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
    tv.setText("sssssssssss sssss ssssss sssssss");
    tv.setTextColor(Color.BLACK);

    TextView tv2 = new TextView(getContext());
    tv2.setText("dua dua dua dua dua dua ");
    tv2.setTextColor(Color.BLACK);
    tv2.setMaxWidth(card.getWidth());

    lin.addView(tv);
    //lin.addView(tv2);
    frame.addView(lin);
    card.addView(frame);

    grid.addView(card);
    col++;
}

3 个答案:

答案 0 :(得分:0)

如果我了解您想要获得的内容,那么问题应该是文本视图的宽度不受限制。 尝试设置ems并启用水平滚动。.

tv.setEms(10);
tv.setHorizontallyScrolling(true);

答案 1 :(得分:0)

要获得所需的布局, 您可以在Recyclerview中使用GridLayoutManager。

以下是该链接 https://developer.android.com/reference/android/support/v7/widget/GridLayoutManager

以下是相同的示例 https://www.journaldev.com/13792/android-gridlayoutmanager-example

答案 2 :(得分:0)

最后我可以使用它

transaction_type