简体   繁体   English

将TextView动态对齐到水平LinearLayout中的下一行

[英]Dynamically align TextView to next line in horizontal LinearLayout

I am adding TextView dynamically using for loop to LinearLayout which orientation is horizontal. 我正在使用for循环动态添加TextViewLinearLayout ,其方向是水平的。 Is it possible to align the TextView to second line if it reach end of screen width? 如果TextView到达屏幕宽度的末尾,是否可以将TextView对齐到第二行?

You can do it in the following manner: 您可以通过以下方式执行此操作:

LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        LinearLayout layout = new LinearLayout(this);
        LinearLayout layout1 = new LinearLayout(this);
        LinearLayout layout2 = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout1.setOrientation(LinearLayout.HORIZONTAL);
        layout2.setOrientation(LinearLayout.HORIZONTAL);

        for (int i = 0; i < 3; i++) {

            TextView lblView = new TextView(this);
            TextView lblView2 = new TextView(this);
            lblView.setLayoutParams(params);
            lblView.setText("hello");
            lblView.setEms(5);
            lblView.setGravity(Gravity.CENTER);
            lblView2.setLayoutParams(params);
            lblView2.setText("hello");
            lblView2.setEms(5);
            lblView2.setGravity(Gravity.CENTER);
            layout1.addView(lblView);
            layout2.addView(lblView2);
        }
        layout.addView(layout1);
        layout.addView(layout2);
        setContentView(layout);

The following will do the trick, 以下将做到这一点,

textview.setLayoutParams(new LayoutParams(
                            LayoutParams.MATCH_PARENT,
                            LayoutParams.WRAP_CONTENT));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM