其他分享
首页 > 其他分享> > android – 挂钩LayoutInflater并在膨胀视图时更改值

android – 挂钩LayoutInflater并在膨胀视图时更改值

作者:互联网

我想实现一个自定义LayoutInflater来缩放维度值,例如,
使用:

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

将使所有维度值加倍的xml膨胀.

也就是说,像这样的xml:

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

将膨胀到宽度和高度为20dp的视图.

LayoutInflater.Factory无法解决我的问题.

我有办法实现这个目标吗?

解决方法:

也许您可以使用此代码循环膨胀布局的所有子代,并通过设置LayoutParams来乘以宽度和高度:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    MyInflater inflater = new MyInflater(LayoutInflater.from(this), this);
    ViewGroup viewGroup = (ViewGroup) findViewById(R.id.my_layout);
    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);
    }

    @Override
    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 {
            doubleDimensions(viewRoot);
        }
        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);
        view.setLayoutParams(params);
    }

    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 {
                doubleDimensions(child);
            }
        }
    }
}

标签:android,layout-inflater
来源: https://codeday.me/bug/20190830/1768362.html