Android - 多行线性布局 [英] Android - multi-line linear layout

查看:27
本文介绍了Android - 多行线性布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个多行布局,它将表现为水平线性布局,但是当没有足够的空间来放置新的小部件时,它会扩展到下一行,就像文本中的单词一样.小部件将在运行时添加到那里,并且应该与 wrap_content 一起使用.实际上,会有按钮.

I need a multi-line layout, which would behave as horizontal linear layout, but when there is not enough space to place new widget it would expand to next line, just like words in text. Widgets would be added there at runtime, and should go with wrap_content. Actually, there would be buttons.

是否有任何具有这种行为的小部件?或者给个建议如何自己写这样的布局.

Is there any widgets with such behaviour? Or give a suggestion about how to write such layout by myself.

最后应该是这样的:

推荐答案

检查评论:这将完成工作

Check the comments: this will do the job

/*
*  Copyright 2011 Sherif
*/

private void populateText(LinearLayout ll, View[] views , Context mContext) { 
    Display display = getWindowManager().getDefaultDisplay();
    ll.removeAllViews();
    int maxWidth = display.getWidth() - 20;

    LinearLayout.LayoutParams params;
    LinearLayout newLL = new LinearLayout(mContext);
    newLL.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT));
    newLL.setGravity(Gravity.LEFT);
    newLL.setOrientation(LinearLayout.HORIZONTAL);

    int widthSoFar = 0;

    for (int i = 0 ; i < views.length ; i++ ){
        LinearLayout LL = new LinearLayout(mContext);
        LL.setOrientation(LinearLayout.HORIZONTAL);
        LL.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM);
        LL.setLayoutParams(new ListView.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        //my old code
        //TV = new TextView(mContext);
        //TV.setText(textArray[i]);
        //TV.setTextSize(size);  <<<< SET TEXT SIZE
        //TV.measure(0, 0);
        views[i].measure(0,0);
        params = new LinearLayout.LayoutParams(views[i].getMeasuredWidth(),
                LayoutParams.WRAP_CONTENT);
        //params.setMargins(5, 0, 5, 0);  // YOU CAN USE THIS
        //LL.addView(TV, params);
        LL.addView(views[i], params);
        LL.measure(0, 0);
        widthSoFar += views[i].getMeasuredWidth();// YOU MAY NEED TO ADD THE MARGINS
        if (widthSoFar >= maxWidth) {
            ll.addView(newLL);

            newLL = new LinearLayout(mContext);
            newLL.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));
            newLL.setOrientation(LinearLayout.HORIZONTAL);
            newLL.setGravity(Gravity.LEFT);
            params = new LinearLayout.LayoutParams(LL
                    .getMeasuredWidth(), LL.getMeasuredHeight());
            newLL.addView(LL, params);
            widthSoFar = LL.getMeasuredWidth();
        } else {
            newLL.addView(LL);
        }
    }
    ll.addView(newLL);
}

这篇关于Android - 多行线性布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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