我想实现一个自定义的 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 - Hook LayoutInflater 并在膨胀 View 时更改值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25997883/