gpt4 book ai didi

android - 挂接 LayoutInflater 并在 inflatedView 时更改值

转载 作者:太空宇宙 更新时间:2023-11-03 12:53:19 25 4
gpt4 key购买 nike

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

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

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

也就是像这样的xml:

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

将膨胀为宽度和高度为 20dp 的 View 。

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 - 挂接 LayoutInflater 并在 inflatedView 时更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25997883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com