【问题标题】:Android initiate custom view with AttributeSet programmaticallyAndroid 以编程方式使用 AttributeSet 启动自定义视图
【发布时间】:2013-09-23 07:58:40
【问题描述】:

您好,我创建了名为 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 对象并在其中设置我的自定义属性

【问题讨论】:

  • 可以添加一个只有Context作为参数的构造函数,然后调用不同视图的setter

标签: android android-custom-view


【解决方案1】:

嗯,当您从 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. 我实际上并不同意,因为这样你就可以将ViewModel 分开,这是编程中的基础设计模式。

【讨论】:

    猜你喜欢
    • 2017-06-18
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多