16

Viewxml レイアウトで宣言され、ビューのコンストラクター中に読み込まれるカスタムのスタイル可能な属性を作成したカスタム がいくつかあります。私の質問は、xml でレイアウトを定義するときにすべてのカスタム属性に明示的な値を指定しない場合、スタイルとテーマを使用して、Viewコンストラクターに渡されるデフォルト値を設定するにはどうすればよいですか?

例えば:

attrs.xml:

<declare-styleable name="MyCustomView">
    <attr name="customAttribute" format="float" />
</declare-styleable>

layout.xml (android:簡単にするためにタグを削除):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.mypackage" >

    <-- Custom attribute defined, get 0.2 passed to constructor -->

    <com.mypackage.MyCustomView
        app:customAttribute="0.2" />

    <-- Custom attribute not defined, get a default (say 0.4) passed to constructor -->

    <com.mypackage.MyCustomView />

</LinearLayout>
4

1 に答える 1

15

さらに調査を行った後、コンストラクターView自体にデフォルト値を設定できることに気付きました。

public class MyCustomView extends View {

    private float mCustomAttribute;

    public MyCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray array = context.obtainStyledAttributes(attrs,
            R.styleable.MyCustomView);
        mCustomAttribute = array.getFloat(R.styleable.MyCustomView_customAttribute,
            0.4f);

        array.recycle();
    }
}

デフォルト値は、xml リソース ファイルからロードすることもできます。これは、画面サイズ、画面の向き、SDK バージョンなどに基づいて変更できます。

于 2012-09-28T08:02:19.463 に答える