2014-01-16 24 views
1

我現在試圖通過某種方式解決TextView中重疊文本的問題。 I've posted a question about that,但我也試圖自己解決它。我決定計算導致textview突破的文本數量。我想出了這個未完成的代碼,它基本上應該誇大視圖,根據顯示的大小設置它的佈局參數,然後運行onmeasure並返回lineCount。我計劃比使用可能的二進制搜索來找到適合textview的確切文本長度,但是甚至在我剛剛嘗試運行代碼並查看其行爲之前。這有點奇怪,因爲它給了我不同的結果,而不是我在屏幕上看到的結果。我甚至試圖根據比例密度來改變文本大小,因爲我不確定它是否被考慮在內。爲什麼我在代碼中運行TextView.measure()時出現不同的結果,從我在屏幕上看到的呈現

這是代碼。它返回三個,但是當我渲染布局來屏幕時,文本只佔用兩行。

public int getCountOfLines(Context context, int widgetDp){ 

    LayoutInflater mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    LinearLayout layout = (LinearLayout) mLayoutInflater.inflate(R.layout.event_basic_large ,null, false); 

    TextView titleTextView = (TextView) layout.findViewById(R.id.itemTitle); 
    titleTextView.setText(TEST_TEXT); 

    float density = context.getResources().getDisplayMetrics().density; 
    float textDensity = context.getResources().getDisplayMetrics().scaledDensity; 

    titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, titleTextView.getTextSize()/density*textDensity); 

    layout.setLayoutParams(
      new LinearLayout.LayoutParams(
        (int) (widgetDp*density), 
        ViewGroup.LayoutParams.WRAP_CONTENT) 
    ); 


    layout.measure(View.MeasureSpec.makeMeasureSpec(
      (int) (widgetDp*density), View.MeasureSpec.EXACTLY), 
      View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) 
    ); 

    Log.d(TAG, titleTextView.getLineCount() + " lines, width "+titleTextView.getMeasuredWidth()); 


    return titleTextView.getLineCount(); 
} 

回答

1

我就遇到了這個而回,尋找和嘗試後,終於得到了下面的函數工作:

public int getLineCount(String testString, float textSize, 
     float width) { 
    Rect bounds = new Rect(); 
    Paint paint = new Paint(); 
    paint.setTypeface(<font>);//set font that you are using for this 
    paint.setTextSize(textSize); 
    paint.getTextBounds(testString, 0, testString.length(), bounds); 

    return (int) Math.ceil(bounds.width()/width); 
} 

此功能使用TEXTSIZE和寬度給行數。 該功能在顯示文本視圖之前給出了行數。

+0

爲什麼你給textview引用作爲參數?看起來不錯,但我仍然瘋狂爲什麼我的代碼做它的作用:/ – simekadam

+1

我有一個TextView的使用,但只是計數線它不是必需的。 –

+0

這種方法是相當有趣的,因爲它給了我確切的比例..我可以很容易地修剪文本..謝謝你 – simekadam

相關問題