网格布局输出“不一致的约束”调试级别日志

27

我已经使用GridLayout几个星期了,我注意到当我调用

gridLayout.requestLayout()

在 LogCat 中,它会输出以下调试级别的消息:

D/android.widget.GridLayout(14048): horizontal constraints: x5 - x0 > 1115, x5 - x4 < 221, x4 - x3 < 221, x3 - x2 < 221, x2 - x1 < 221, x1 - x0 < 221 are inconsistent; permanently removing: x5 - x4 < 221. 

我查看了GridLayout的源码,试图找出“约束不一致”的可能原因,但我没能弄清楚。

这些消息的出现是否值得我关注?我没有看到任何布局方面的问题。在我的Fragment中有一个GridLayout,作为ViewPager中加载的页面,当用户在页面之间滚动时,我会在LogCat中多次看到上述输出。


希望这对你有所帮助:https://dev59.com/9Zjga4cB1Zd3GeqPIU9d?noredirect=1&lq=1 - Naresh Palle
4个回答

14

GridLayout 源代码中:

使用 Bellman-Ford 算法的变体,修改后将典型运行时间从 O(N^2) 降低到 O(N)

GridLayout 将其要求转换为以下形式的线性约束系统:

x[i] - x[j] < a[k]

其中x[i]是变量,a[k]是常量。

例如,如果变量被标记为xyz,我们可能会有:

x - y < 17
y - z < 23
z - x < 42

这是线性规划问题的一个特殊情况,反过来等同于在有向图上的单源最短路径问题,其中 O(n^2) Bellman-Ford 算法是最常用的通用解决方案。

它有一个 solve 方法,使用线性规划来保证其配置所必须满足约束条件的一致性。如果您找出与约束条件 x5 - x4 < 221 关联的配置并将其删除,则可以提高布局性能。然后求解器就不必再解决无法满足的问题并自行删除它。


5

我遇到了同样的问题,后来发现我忘记添加XML命名空间了。我通过以下方式进行了更正:

<android.support.v7.widget.GridLayout 
     xmlns:grid="http://schemas.android.com/apk/res-auto"
     xmlns:android="http://schemas.android.com/apk/res/android">
...
</android.support.v7.widget.GridLayout>

然后还将兼容性GridLayout使用的属性前缀与XML命名空间一起更改:

<ImageButton android:id="@+id/btnSentence"
    grid:layout_row="0"
    grid:layout_column="0"
    ...
/>

它对我有帮助,希望它也能对你有所帮助。


我尝试了这个,但似乎仍然有同样的问题。我没有使用兼容性库——这可能是不同之处。谢谢。 - mdupls

2
我通过将GridLayout的宽度使用wrap_content而非match_parent来解决了问题,我猜这样就减少了一个约束。"最初的回答"

0
对我来说,我正在使用GridLayout创建自定义视图。
问题是我认为我可以在xml中设置网格的列数。
我的布局XML如下所示:
<merge xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"

        app:alignmentMode="alignMargins"
        app:columnCount="9"
        app:columnOrderPreserved="true"
        tools:ignore="HardcodedText"
        app:orientation="horizontal"
        tools:parentTag="androidx.gridlayout.widget.GridLayout"
        app:rowOrderPreserved="true">

        ...

</merge>

很遗憾,对于自定义布局来说并不是这样工作的。我不得不在我的自定义视图中指定所有那些属性,在命名空间app中像这样:

class SimpleCalculatorView(context: Context, attrs: AttributeSet?): GridLayout(context, attrs) {

  init {
    ...

    View.inflate(context, R.layout.view_simple_calculator, this)
    columnCount = 9
    columnOrderPreserved = true
    rowOrderPreserved = true
    orientation = HORIZONTAL
}

做完这个之后,我不再遇到错误了。

编辑

我说得太早了。错误又出现了,这次是每当我在MotionLayout中动画自定义布局时发生的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接