Capturing LayoutInflater and changing values ​​while inflating views

I want to implement a custom LayoutInflater that scales dimension values ​​like Application:

int scale = 2;
MyInflater.inflate(, null, parent, scale);


will inflate the xml with all sizing values ​​doubled.

that is, xml like this:

<View android:layout_width="10dp" android:layout_height="10dp" />


will bloat to presenting that the width and height are 20dp.


can't solve my problem.

Is there a way I can achieve this?


source to share

1 answer

Perhaps you could use this code to encode all the children of your inflated layout and multiply the width and height by setting LayoutParams:

protected void onCreate(Bundle savedInstanceState) {

    MyInflater inflater = new MyInflater(LayoutInflater.from(this), this);
    ViewGroup viewGroup = (ViewGroup) findViewById(;
    inflater.inflate(R.layout.test_view, viewGroup, true, 2);

private class MyInflater extends LayoutInflater {

    private int mScale;

    protected MyInflater(LayoutInflater original, Context newContext) {
        super(original, newContext);

    public LayoutInflater cloneInContext(Context newContext) {
        return null;

    public View inflate(int resource, ViewGroup root, boolean attachToRoot, int scale) {
        mScale = scale;
        // This will return the parent of the inflated resource (if it has one)
        View viewRoot = super.inflate(resource, root, attachToRoot);

        if (viewRoot instanceof ViewGroup) {
            loopViewGroup((ViewGroup) viewRoot, viewRoot == root);
        } else {
        return viewRoot;

    private void doubleDimensions(View view) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        Log.d(TAG, "Before => "+params.width+" : "+params.height);
        params.width = params.width * mScale;
        params.height = params.height * mScale;
        Log.d(TAG, "After => "+params.width+" : "+params.height);

    private void loopViewGroup(ViewGroup group, boolean isRoot) {
        // If viewRoot == root, skip setting ViewGroup params
        if (!isRoot) doubleDimensions(group);

        // Loop the ViewGroup children
        for (int i=0; i<group.getChildCount(); i++) {
            View child = group.getChildAt(i);
            // If a child is another ViewGroup, loop it too
            if (child instanceof ViewGroup) {
                loopViewGroup((ViewGroup) child, false);
            } else {




All Articles