Android 以编程方式使用 AttributeSet 启动自定义视图

问题描述 投票:0回答:1

嗨,我已经创建了简单的自定义视图,称为

Group

public class Group extends LinearLayout {

    private TextView headerTextView;

    public Group(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.Group, 0, 0);
        String string = typedArray.getString(R.styleable.Group_headerText);
        typedArray.recycle();
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.widget_group, this, true);

        headerTextView = (TextView) v.findViewById(R.id.header_text);
        headerTextView.setText(string);

    }


}

我想在活动中动态创建它。我想设置我的自定义属性属性。 我找到了一些充气的解决方案,但我真的不想使用它;这不是创建对象的正确方法。 我需要一个关于这个领域的例子

Group g = new Group(v.getContext(),arrt);

只是不知道如何设置 arrt 对象并在其中设置我的自定义属性

android android-custom-view
1个回答
0
投票

好吧,当您从 XML 扩展视图时,通常会使用此构造函数。如果您需要动态创建自定义视图,则提供一个没有属性集的新构造函数,只有一个

Context
并在那里膨胀XML:

public Group(Context context) {
    super(context, attrs);
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.widget_group, this, true);

    headerTextView = (TextView) v.findViewById(R.id.header_text);
}

您还需要一个单独的公共方法来提供标题文本:

public void setHeader(String header) {
    headerTextView.setText(header);
}

动态创建此类的任何人都会调用它。

I found some solution with inflating but I really don't want to use that; it's not proper way to create object.
我实际上并不同意,因为这样你就把
View
Model
分开了,这是编程中的基础设计模式。

© www.soinside.com 2019 - 2024. All rights reserved.