2

こんにちは、次のような単純なカスタム ビューを作成しました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 オブジェクトを設定してカスタム属性を設定する方法がわかりませんでした

4

1 に答える 1

0

このコンストラクターは通常、XML からビューを拡張するときに使用されます。カスタム ビューを動的に作成する必要がある場合は、属性を設定せずに a のみを指定して新しいコンストラクターを提供し、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 メソッドも必要です。

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.私は実際には同意しません。なぜなら、このようにして、プログラミングの基本的な設計パターンである whichViewから分離しているからです。Model

于 2013-09-23T08:05:36.290 に答える