6

カスタム コンポーネントについて学んでいますが、カスタム xml 属性に問題があります。
私のカスタム コンポーネントは LinearLayout を拡張し、constructor( public Custom(Context context, AttributeSet attrs)) で xml レイアウト (2 つのボタンと 1 つの EditText) を拡張しています。このカスタム属性
でも宣言しました:values/attrs

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Custom">
        <attr name="initValue" format="integer" />
        <attr name="stepSize" format="integer" />
        <attr name="maxValue" format="integer"/>
    </declare-styleable>
</resources>


レイアウトを膨らませた後のコンストラクターで、次のようにカスタム属性を読み取ろうとしています。

   if (attrs != null) {
                TypedArray ta = context.obtainStyledAttributes(attrs,
                        R.styleable.Custom, 0, 0);
                setInitValue(ta.getInt(R.styleable.Custom_initValue, 0));
                setStepSize(ta.getInt(R.styleable.Custom_stepSize, 1));
                setMaxValue(ta.getInt(R.styleable.Custom_maxValue, 5));         
                ta.recycle();
            }


次に、このカスタム コンポーネントを次のような xml レイアウトに追加してテストします。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <here.is.my.package.Custom android:id="@+id/add"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        initValue="2" maxValue="7" stepSize="1" />
</LinearLayout>


これは機能せず、デフォルト値 (0、1、5) のみを取得します。何か足りないのですか、それともこれは正常な動作ですか?

4

2 に答える 2

8

わかりました、私は私の質問に対する答えを考え出しました。答えは、名前空間なしでカスタム xml 属性を使用しただけで、Android はそれらを無視してデフォルト値を与えたというものでした。名前空間を追加した後:

   <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:customAttribute="http://schemas.android.com/apk/res/gere.is.my.package"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <here.is.my.package.Custom android:id="@+id/add"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            customAttribute:initValue="2" customAttribute:maxValue="7" customAttribute:stepSize="1" />
    </LinearLayout>

すべてが機能しました。

于 2011-09-19T14:49:05.897 に答える
4

Gradle プロジェクトでは、

xmlns:customView="http://schemas.android.com/apk/res-auto"

これは私のために働く!

于 2016-03-14T10:10:56.457 に答える