CustomLayout的子视图中出现意外的名称空间前缀应用

时间:2018-10-15 01:50:15

标签: android android-custom-view

CustomLayout的子视图中使用属性时出现错误(我定义了一个自定义LayoutParams,以允许子视图使用此属性)

enter image description here

但是,代码仍然正在运行并显示正确的值(您可以在下面检查我的代码,当我运行应用程序时,它将在logcat中显示“ Hello”)

这是我的代码 style.xml

<declare-styleable name="CustomRelativeLayout_Layout">
     <attr name="title" format="string" />
</declare-styleable>

CustomRelativeLayout类

public class CustomRelativeLayout extends RelativeLayout {

    public CustomRelativeLayout(Context context) {
        this(context, null);
    }

    public CustomRelativeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new CustomLayoutParams(getContext(), attrs);
    }

    @Override
    public void onViewAdded(View child) {
        super.onViewAdded(child);
        CustomLayoutParams layoutParams = (CustomLayoutParams) child.getLayoutParams();
        Log.i("TAG", "title = " + layoutParams.title);
    }

    final class CustomLayoutParams extends RelativeLayout.LayoutParams {
        String title;

        CustomLayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
            TypedArray ta =
                    c.obtainStyledAttributes(attrs, R.styleable.CustomRelativeLayout_Layout);
            title = ta.getString(R.styleable.CustomRelativeLayout_Layout_title);
            ta.recycle();
        }
    }
}

当然,我可以通过添加tools:ignore="MissingPrefix"来禁用它,但是我不太喜欢。任何帮助或建议将不胜感激。

这是我的演示https://github.com/PhanVanLinh/AndroidPassAttributeToChildVIew

1 个答案:

答案 0 :(得分:1)

经过多次尝试,我找到了解决问题的方法

title更改为layout_title将使错误消失

<declare-styleable name="CustomRelativeLayout_Layout">
     <attr name="title" format="string" />
</declare-styleable>

魔术layout_,因为如果我这样使用,错误仍然会发生 title_title_dasdasdsadlo_titletitle_23232