android layoutinflater 高度,android – 挂钩LayoutInflater并在膨胀视图时更...

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

使用:

int scale = 2;

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

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

也就是说,像这样的xml:

将膨胀到宽度和高度为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

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);

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值