0

我做了ScrollView并在里面LinearLayout放了一个TextView,我只想在里面放一个字符串,直到TextView超出布局。我的代码的问题是while循环永远不会结束。

public class MainActivity extends Activity {
public static int screenWidth,screenHeight;
public boolean overlap;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main) ;



    ScrollView scroll=(ScrollView) findViewById(R.id.scrollView1);
    TextView mytextview=(TextView) findViewById(R.id.textview1);
    TextView textshow=(TextView) findViewById(R.id.textView2);
    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearlayout);

    mytextview.setText("");

    ViewTreeObserver vto=scroll.getViewTreeObserver();
    getmeasure(vto,mytextview,scroll,linearLayout);
}



public void getmeasure(ViewTreeObserver vto, final TextView mytextview2, final ScrollView scroll2, final LinearLayout linearLayout2) {


    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            int a=linearLayout2.getMeasuredHeight();
            int b=scroll2.getHeight();

            while (a<b) {
                mytextview2.append("full    full    full");
                a=linearLayout2.getMeasuredHeight();
                b=scroll2.getHeight();
                }

            }
    });

}
4

1 回答 1

0

getMeasuredHeight() 方法返回在 onMeasure() 中测量的高度。您的代码的问题是, getMeasuredHeight() 不会改变,因为 Android 框架没有调用 onMeasure()。实际上,您的 while 循环会阻止框架测量视图。

像这样实现 OnGlobalLayoutListener:

vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        int a=linearLayout2.getMeasuredHeight();
        int b=scroll2.getHeight();

        if (a<b) {
            mytextview2.append("full    full    full");       
        }

   }
});

在布局后添加文本时,LinearLayout 及其父级 (ScrollView) 应该会失效,因此视图将再次布局。布局包括测量视图。这意味着您的 OnGlobalLayoutListener 将再次被调用。

请注意,这不是用文本填充屏幕的好方法。实际上,您不需要 ScrollView 来使 TextView 垂直滚动。如果你不希望它的内容高于屏幕,为什么你甚至需要一个 ScrollView?

于 2013-05-22T09:20:49.337 回答