Home  >  Article  >  Java  >  How to Implement Line-Breaking Layout for Widgets in Android?

How to Implement Line-Breaking Layout for Widgets in Android?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-07 02:01:03793browse

How to Implement Line-Breaking Layout for Widgets in Android?

Line-Breaking Widget Layout for Android

Issue:

In an Android application, you may have data that can be divided into widgets, each representing a word. To display this data, you want to arrange the widgets in lines, similar to a text paragraph, allowing them to wrap to the next line when necessary.

Proposed Solution:

Implement a custom layout known as PredicateLayout that mimics the line-breaking behavior of text. This layout manages child views by arranging them in lines, wrapping when the end of the line is reached.

Code Sample:

public class PredicateLayout extends ViewGroup {
    private int line_height;

    // ...

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // ...
        for (int i = 0; i < count; i++) {
            // ...
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
            // ...
            line_height = Math.max(line_height, child.getMeasuredHeight() + lp.height);
            // ...
        }
        this.line_height = line_height;
        // ...
    }

    // ...
}

Usage:

Within an activity, you can use this custom layout as follows:

public class MyActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // ...
        PredicateLayout l = new PredicateLayout(this);
        // ...
        setContentView(l);
    }
}

Result:

The PredicateLayout effectively arranges the widgets in lines, wrapping to the next line when the width constraint is exceeded. This allows for the display of data as wrapped text-like paragraphs.

The above is the detailed content of How to Implement Line-Breaking Layout for Widgets in Android?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn