Android Open Source - tdpforce Dynamic Height Text View

From Project

Back to project page tdpforce.


The source code is released under:

Apache License

If you think the Android project tdpforce listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

//from   w  w  w  .  jav a2s  .  c  om
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

 * A {@link android.widget.TextView} that maintains a consistent width to height aspect ratio.
 * In the real world this would likely extend ImageView.
public class DynamicHeightTextView extends TextView {

    private double mHeightRatio;

    public DynamicHeightTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

    public DynamicHeightTextView(Context context) {

    public void setHeightRatio(double ratio) {
        if (ratio != mHeightRatio) {
            mHeightRatio = ratio;

    public double getHeightRatio() {
        return mHeightRatio;

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mHeightRatio > 0.0) {
            // set the image views size
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = (int) (width * mHeightRatio);
            setMeasuredDimension(width, height);
        else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);

Java Source Code List