Does Android XML Layout's 'include' Tag Really Work?

前端 未结 3 1615
臣服心动
臣服心动 2020-12-04 09:16

I am unable to override attributes when using in my Android layout files. When I searched for bugs, I found Declined Issue 2863:

\"include tag is bro

3条回答
  •  时光取名叫无心
    2020-12-04 10:05

    I just found the issue. First, you can only override layout_* attributes, so the background won't work. That is documented behavior and simply an oversight on my part.

    The real problem is found in LayoutInflater.java:

    // We try to load the layout params set in the  tag. If
    // they don't exist, we will rely on the layout params set in the
    // included XML file.
    // During a layoutparams generation, a runtime exception is thrown
    // if either layout_width or layout_height is missing. We catch
    // this exception and set localParams accordingly: true means we
    // successfully loaded layout params from the  tag,
    // false means we need to rely on the included layout params.
    ViewGroup.LayoutParams params = null;
    try {
       params = group.generateLayoutParams(attrs);
    } catch (RuntimeException e) {
       params = group.generateLayoutParams(childAttrs);
    } finally {
       if (params != null) {
         view.setLayoutParams(params);
       }
    }
    

    If the tag does not include both layout_width and layout_height, the RuntimeException occurs and is silently handled, without any log statement even.

    The solution is to always include both layout_width and layout_height when using the tag, if you want to override any of the layout_* attributes.

    My example should change to:

    
    

提交回复
热议问题