2012-10-23 108 views
2

您好我想有一個TextView,它具有以下限制:的Android TextView的字體大小後不調整改變

  1. 它可以去最大的2號線,如果是超過2行,它會只是在最後顯示'...'
  2. 從字體大小30開始,我們首先嚐試通過將字體大小從30減小到12來將所有內容放在一行中。這意味着如果我們可以將字體大小設置爲20第一行,我們堅持使用字體大小20
  3. 如果我們不能適應所有字體大小爲12的東西,我們仍然在12號大小,並且我們換行到下一行,並且所有東西都會保持在12號。

所以現在我有一個EditText上,它允許用戶鍵入文本,每個字符的用戶進入,TextView的將反映用戶類型和字體大小相應地改變上述規則。

userEditView.addTextChangedListener(
     new TextWatcher() { 
       @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { 

    float fontSize = 30; 
    userTextView.setTextSize(fontSize); 
    int userTextViewWidth = userTextView.getWidth(); 
    int userTextViewContainerWidth = parentRelatievLayOutView.getWidth();//parentRelativeLayout is a RelativeLayout in xml 


    // logic here => i want to know when to wrap a line, i should wrap when the textView width is same or greater than the parent container, in such case, we reduce the font size, and then get the new textView width, see if it can be fit in one line or not 


     while (userTextViewWidth >= userTextViewContainerWidth) { 
     fontSize -= 1; 
     if (fontSize <= 12) { 
      fontSize = 12; 
      break; 
     } 
     userTextView.setTextSize(fontSize); 

     //userTextView.append("\uFEFF"); // does not work 
     //userTextView.invalidate(); // does not work 
     userTextViewWidth = userTextView.getWidth();// *** this line never gets updated 
     } 


    } 
    @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { 

    userTextView.setText(charSequence); 
    } 
    @Override public void afterTextChanged(Editable editable) { 
    } 
}); 

所以我的問題是userTextViewWidth = userTextView.getWidth()永遠不會被更新,即字體大小變小,寬度還是一樣......我想改變這種狀況 存在與Android的問題,即TextView的大小沒有改變Android:TextView height doesn't change after shrinking the font size但我嘗試過,沒有提供任何技術。

回答

0

設置android:layoutWidth="wrap_content",textview將根據文本長度縮放寬度大小。 AFAIK,沒有辦法根據文本大小自動調整textview的大小。

+0

對不起,您的解決方案不適合我的情況下工作。我有限制,我需要適應儘可能多的字符,因爲我可以在有2行的textview。是的,在android中可能沒有直接的api幫助我,這就是爲什麼我想玩寬度。 – user1697965