比方说,我想构建一个像这样的工具栏: https://i.stack.imgur.com/a15lj.png
因此,工具栏具有最大宽度,我想向工具栏添加项目(搜索,复制等),直到达到最大宽度为止。
挑战在于,如果不实际夸大这些“项目”的规模,我将一无所知。
最好的方法是什么?以下计划听起来不错吗?
CSS
.block__icon {
position: absolute;
z-index: 2; /* New line */
margin: some-corrections;
}
.block__input {
position: relative; /* New line */
z-index: 2; /* New line */
padding: some-corrections;
}
/* New */
.block__input:placeholder-shown {
z-index: 1;
}
谢谢。
答案 0 :(得分:0)
您可以通过编程方式或使用xml布局创建工具栏视图组。如果以编程方式进行操作,则可以在自定义视图组中覆盖onMeasure()并可以测量视图组的子视图,然后在onLayout中,可以根据测量的宽度来布局子视图。
public class Toolbar extends ViewGroup{
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int width = MeasureSpec.getSize(widthMeasureSpec);
final int height = MeasureSpec.getSize(heightMeasureSpec);
// measure child views here
setMeasuredDimension(width, height);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// layout your child views here
View child = getChildAt(0);
child.layout(0, 0, child.getMeasuredWidth, child.getMeasuredHeight());
}
}
如果您希望坚持使用xml布局,则可以使用OnGlobalLayoutListener()。
ViewGroup toolbar = findViewById();
toolbar.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//Layout is now complete so dimens of toolbar and its child views are available
int toolbarW = toolbar.getWidth();
int toolbarH = toolbar.getHeight();
// you can add fixed child views in xml and if space is available add optional child views programmatically
// listener will be called multiple times so do null check before adding views
}
}