我想实现一个自定义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
无法解决我的问题。
我有办法实现这个目标吗?
答案 0 :(得分:5)
也许你可以使用这段代码来循环你的膨胀布局的所有孩子,并通过设置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);
}
}
}
}