2013-05-22 18 views
0

我發ScrollView,在其內部LinearLayout我把TextView, 我只想把字符串放進去,直到TextView超出了佈局。 我的代碼問題是while 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(); 
       } 

      } 
    }); 

} 

回答

0

方法getMeasuredHeight()返回已在onMeasure()中測量的heigth。您的代碼存在的問題是,getMeasuredHeight()不會更改,因爲onMeasure()尚未由Android Framework調用。實際上你的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其父(滾動型)應該得到無效的,因此意見將再次layouted。佈局包括測量視圖。這意味着您的OnGlobalLayoutListener將再次被調用。

請注意,這不是用文本填充屏幕的好方法。實際上,你不需要一個ScrollView來垂直創建一個TextView可滾動的。爲什麼你甚至需要一個ScrollView如果你不想讓它的內容比屏幕更高?

+0

「您的代碼存在的問題是,getMeasuredHeight()不會更改,因爲onMeasure()尚未被Android Framework調用。」謝謝您的回答。 「請注意,這不是一個用文本填充屏幕的好方法」,所以請告訴我一種方法,我想將非常長的文本放入分隔的textView中,並且每個textView都需要整個屏幕。 (每個textView是在一個pageView中,我只是想知道什麼時候打破文字以適合屏幕) 謝謝。 –

+0

我知道這個問題並不容易。但是,您不應該一次又一次地使用Frameworks佈局過程來解決適當的文本量。你可以像在http://stackoverflow.com/questions/14276853/how-to-measure-textview-height-based-on-device-width-and-font-size的答案中測量文本,並搜索正確的文字量。或者使用TextView.getOffsetForPosition()來確定TextView中的最後一個字符,並從下一頁的下一個字符開始。 – thaussma