detect clipping in android TextView

前端 未结 3 1604
天命终不由人
天命终不由人 2021-02-09 04:12

I have a TextView in my android application that has a set width on it. It\'s currently got a gravity of \"center_horitonzal\" and a set textSize (9sp). I pull values to put o

相关标签:
3条回答
  • 2021-02-09 04:54

    Another way to do this (which might be equivalent) is something like this:

            TextView title = new TextView(context) {
                @Override
                protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                    int textsize = 30;
                    setTextSize(textsize);
                    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                    while (getMeasuredHeight() > MeasureSpec.getSize(heightMeasureSpec)) {
                        textsize--;
                        setTextSize(textsize);
                        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                    }
                }
            };
    

    Just a warning that this seems to work, but I just threw it together - might be some edge cases in ways the TextView can be measured.

    0 讨论(0)
  • 2021-02-09 05:00

    I found a way to measure the width of text using the TextView's Paint object, and lower it until it fit in the size I needed. Here's some sample code:

        float size = label.getPaint().measureText(item.getTitle());
        while (size > 62) {
            float newSize = label.getTextSize() - 0.5f;
            label.setTextSize(newSize);
            size = label.getPaint().measureText(item.getTitle());
        }
    
    0 讨论(0)
  • 2021-02-09 05:07

    I wrote this function to trim off letters from the end of the text until it meets a certain width requirement.

    The 0.38 function is setting the proportion of the screen I want to fill with this text, in this case, it was 38% since I wanted it to cover ~40% including padding. Worked for the cases I've tested it with.

    Using this code to call the function below

    DisplayMetrics metrics = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
    
    double maxWidth = (double)metrics.widthPixels*0.38 - 1;
    TextPaint painter = station.getPaint();
    
    String left = item.getLocationName();
    left = trimToLength(painter, left, maxWidth);
    
    
    textView.setText(left);
    

    This is the function

    public String trimToLength(TextPaint painter, String initialText, double width)
    {
        String message = initialText;
        String output = initialText;
    
        float currentWidth = painter.measureText(output);
        while (currentWidth > width)
        {
            message = message.substring(0, message.length()-1);
    
            output = message + "...";
    
            currentWidth = painter.measureText(output);
        }
    
        return output;
    }
    
    0 讨论(0)
提交回复
热议问题