Find string which width is optimal to the TextView. - Android User Interface

Android examples for User Interface:TextView

Description

Find string which width is optimal to the TextView.

Demo Code

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import android.widget.TextView;

public class Main {
  private static final Comparator<String> lengthComparator = new Comparator<String>() {
    @Override/* w w  w  .ja  v  a 2 s . c o m*/
    public int compare(String lhs, String rhs) {
      return lhs.length() - rhs.length();
    }
  };

  /**
   * Find string which width is optimal to the TextView.
   * 
   * @param textView
   *          can be not measured yet
   * @param width
   *          value to compare with strings width
   * @param strings
   *          can be unsorted
   * @return optimal width string from width
   */
  public static String getOptimalWidthString(final TextView textView,
      int width, final String... strings) {
    List<String> collection = Arrays.asList(strings);
    if (!isSorted(collection, lengthComparator))
      Collections.sort(collection, lengthComparator);
    Iterator<String> i = collection.iterator();
    String result = i.next();
    String current;
    while (i.hasNext() && getTextSize(textView, current = i.next()) < width) {
      result = current;
    }
    return result;
  }

  private static <T extends Comparable> boolean isSorted(Iterable<T> iterable,
      Comparator<T> comparator) {
    T previous = null;
    for (T t : iterable) {
      if (previous != null && comparator.compare(previous, t) < 0)
        return false;
      previous = t;
    }
    return true;
  }

  /**
   * Return the width of the testText.
   * 
   * @return the width of testText placed in the textView
   */
  private static float getTextSize(TextView textView, String testText) {
    return textView.getPaint().measureText(testText);
  }
}

Related Tutorials