也許你可以使用此代碼迴路所有孩子的充氣佈局和設置的LayoutParams乘以寬度和高度:「LayoutInflater.Factory解決不了我的問題」
@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);
}
}
}
}
- 爲什麼不? – CommonsWare 2014-09-23 14:40:10
@CommonsWare如果使用'LayoutInflater.Factory',我必須自己創建每個視圖,因爲沒有鏈接超級調用;並且LayoutParams生成不在'createViewFromTag()'中,Factory的'onCreateView()'被調用,所以在Factory的'onCreateView()'中,修改LayoutParams是不可能的。 – bladefury 2014-09-24 02:37:04
我不太明白這個問題,你想膨脹時從xml的視圖縮放? – 2014-09-27 08:05:23