如何在LinearLayout中膨胀新视图之前检查是否有可用空间?

时间:2017-06-23 19:46:40

标签: android android-layout layout android-linearlayout layout-inflater

我的Activity底部有一个片段,可以填充单词(views)。
这是片段的图像:

enter image description here

在蓝色按钮之间,您可以通过单击位于此片段上方的GridView中的项目来扩充视图。每次我点击一个项目的文字视图:正在添加“测试”。它从膨胀视图开始,直到它不再适合LinearLayout。

当LinearLayout已满时,它看起来像这样:enter image description here

当布局看起来已满时,您仍然可以对视图进行充气,但不会再看到它们被添加。 你可以在上面的图像上看到的最右边的紫色视图比其他的更高,因为它不再适合。

我想检查LinearLayout中是否有足够的空间来膨胀新视图。 这是扩展LinearLayout中视图的代码:

public void inflateAllViews(){
    LayoutInflater inflaterr = (LayoutInflater) MainApplication.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    linearLayout.removeAllViews();

    ArrayList<WordTile> wordsToInflate = WordManager.getWordsToInflate();
    for(WordTile WordTile : wordsToInflate){
        View word = inflaterr.inflate(R.layout.word, null);
        final TextView textView = (TextView)word.findViewById(R.id.text_word);
        textView.setText(WordTile.getTitle());

        linearLayout.addView(word);
    }
}

但是我需要检查是否可以添加视图,因为没有剩余空间。因为在后台,您可以向LinearLayout添加无限制的视图。

我试图找到一种计算膨胀视图宽度的方法。我发现的唯一一件事是:

ViewTreeObserver vto = word.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Log.d("TEST", "Height = " + word.getHeight() + " Width = " + word.getWidth());
                widthOfChildren += word.getWidth();
                System.out.println("widthofchildren:" + widthOfChildren);
                ViewTreeObserver obs = word.getViewTreeObserver();
                obs.removeGlobalOnLayoutListener(this);
            }
        });

代码工作并打印每个视图所需的宽度。但我不能使用OnGlobalLayoutListener ....之外的宽度。

有没有人能解决我的问题?

编辑:

问题不在于LinearLayout的宽度,因为我知道宽度,它是LinearLayout中视图的宽度。 LinearLayout的标准宽度不会改变。

0 个答案:

没有答案
相关问题