Get TextView's height, TextView's width is full screen width - Android User Interface

Android examples for User Interface:TextView

Description

Get TextView's height, TextView's width is full screen width

Demo Code

/*//from  w  w  w .  java 2s .co  m
 * Copyright (C) 2016 venshine.cn@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.view.Display;
import android.view.View;

import android.view.WindowManager;

import android.widget.TextView;

public class Main {
    /**
     * Get TextView's height, TextView's width is full screen width
     *
     * @param textView
     * @return
     */
    public static int getTextViewHeight(TextView textView) {
        WindowManager wm = (WindowManager) textView.getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();

        int deviceWidth;

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            Point size = new Point();
            display.getSize(size);
            deviceWidth = size.x;
        } else {
            deviceWidth = display.getWidth();
        }

        return getTextViewHeight(textView, deviceWidth);
    }

    /**
     * Get TextView's height by textview's width
     *
     * @param textView
     * @param width
     * @return
     */
    public static int getTextViewHeight(TextView textView, int width) {
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(width,
                View.MeasureSpec.AT_MOST);
        int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        textView.measure(widthMeasureSpec, heightMeasureSpec);
        return textView.getMeasuredHeight();
    }
}

Related Tutorials