以编程方式将TextView添加到Grid Layout对齐方式不正确 [英] Programmatically adding TextView to Grid Layout alignment not proper

查看:75
本文介绍了以编程方式将TextView添加到Grid Layout对齐方式不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将具有drawableLeft的TextView添加到GridLayout中。
我正在循环中添加此TextView。正在正确添加TextView,但未正确对齐。每个textview在水平行上都应采用相等的宽度,这不会发生。

Hi i am trying to add TextView with drawableLeft to GridLayout. I am adding this TextView in an Loop. The TextView are getting added properly but the are not aligned properly. Each textview should take equal width in one horizontal row which is not happening.

以下是我正在使用的代码

Following is the code i am using

    GridLayout gridLayout = new GridLayout(getContext());
            gridLayout.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
            gridLayout.setColumnCount(2);
            gridLayout.setRowCount(3);
            TextView titleText;
            for (int i = 0; facilities != null && i < facilities.size(); i++) {
                titleText = new TextView(getContext());
                titleText.setText(facilities.get(i));
                gridLayout.addView(titleText, i);
                titleText.setCompoundDrawablesWithIntrinsicBounds(rightIc, 0, 0, 0);
}


推荐答案

为此,您必须动态设置视图的列宽。

For this you have to dynamically set the column width for the views. This will finally align each view properly with equal amount of space.

GridLayout gridLayout = new GridLayout(getContext());
            gridLayout.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
            gridLayout.setColumnCount(2);
            gridLayout.setRowCount(3);
            TextView titleText;
            for (int i = 0; facilities != null && i < facilities.size(); i++) {
                titleText = new TextView(getContext());
                titleText.setText(facilities.get(i));
                gridLayout.addView(titleText, i);
                titleText.setCompoundDrawablesWithIntrinsicBounds(rightIc, 0, 0, 0);
                GridLayout.LayoutParams param =new GridLayout.LayoutParams();
                param.height = LayoutParams.WRAP_CONTENT;
                param.width = LayoutParams.WRAP_CONTENT;
                param.rightMargin = 5;
                param.topMargin = 5;
                param.setGravity(Gravity.CENTER);
                param.columnSpec = GridLayout.spec(c);
                param.rowSpec = GridLayout.spec(r);
                titleText.setLayoutParams (param);

} 

这篇关于以编程方式将TextView添加到Grid Layout对齐方式不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆