从约束布局循环设置视图子项的重力

时间:2019-01-13 13:38:09

标签: java android android-view textview android-constraintlayout

当我访问由TextView循环动态创建为ConstraintLayout的子代时,它们将以View的形式返回,而没有setGravity

有人知道一种设置这些视图的重力(TextView /子视图的重力,而不是布局)的方法吗?

for (int i = 0;i < constraintLayout.getChildCount();i++) {
    final View child = constraintLayout.getChildAt(i);
    Object tag = child.getTag(R.id.tagId);
    if(tag != null) {
        //child.setGravity(Gravity.START); // Doesn't work...
    } else {} }

我看不到用于设置Gravity的任何选项 ConstraintLayout.LayoutParamsConstraintSet

另外,我尝试了final TextView child = (TextView) constraintLayout.getChildAt(i);:但是,这导致了致命的异常: java.lang.ClassCastException:android.widget.ImageView无法转换为android.widget.TextView 。注意:子级是textviews,不是imageviews ...

1 个答案:

答案 0 :(得分:1)

首先将视图投射到TextView,然后调用setGravity

final View child = constraintLayout.getChildAt(i);
Object tag = child.getTag(R.id.tagId);
if (tag != null) {
    if (child instanceof TextView) {
        TextView tv = (TextView) child;
        tv.setGravity(Gravity.START);
    }
} else {}