get Target View Width via reflection - Android User Interface

Android examples for User Interface:View Size

Description

get Target View Width via reflection

Demo Code


//package com.java2s;
import java.lang.reflect.Method;
import android.view.View;
import android.view.View.MeasureSpec;

public class Main {
    public static int getTargetWidth(View v) {

        try {//from w  ww .j av a 2s. c  o  m
            Method m = v.getClass().getDeclaredMethod("onMeasure",
                    int.class, int.class);
            m.setAccessible(true);
            m.invoke(v, MeasureSpec.makeMeasureSpec(
                    ((View) v.getParent()).getMeasuredWidth(),
                    MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0,
                    MeasureSpec.UNSPECIFIED));
        } catch (Exception e) {

        }
        return v.getMeasuredWidth();
    }
}

Related Tutorials