60

XML レイアウトからNumberPickerの最小値、最大値、およびデフォルト値を設定する方法はありますか?

私はアクティビティコード内からそれをやっています:

np = (NumberPicker) findViewById(R.id.np);
np.setMaxValue(120);
np.setMinValue(0);
np.setValue(30);

XML は、動作ではなくプロパティを定義するため、明らかにより適切です。

XML レイアウトを使用してこれらを設定する方法はありますか?

4

3 に答える 3

59

私は同じ問題を抱えていました.これは私がそれを解決した方法です(MKJParekhのコメントによると):

  1. 独自の NumberPicker-Class を作成しました

    package com.exaple.project;
    
    import android.annotation.TargetApi;
    import android.content.Context;
    import android.os.Build;
    import android.util.AttributeSet;
    import android.widget.NumberPicker;
    
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)//For backward-compability
    public class MyNumberPicker extends NumberPicker {
    
        public MyNumberPicker(Context context) {
            super(context);
        }
    
        public MyNumberPicker(Context context, AttributeSet attrs) {
            super(context, attrs);
            processAttributeSet(attrs);
        }
    
        public MyNumberPicker(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            processAttributeSet(attrs);
        }
        private void processAttributeSet(AttributeSet attrs) {
            //This method reads the parameters given in the xml file and sets the properties according to it
            this.setMinValue(attrs.getAttributeIntValue(null, "min", 0));
            this.setMaxValue(attrs.getAttributeIntValue(null, "max", 0));
        }
    }
    
  2. これで、この NumberPicker を xml レイアウト ファイルで使用できます

    <com.exaple.project.myNumberPicker
        android:id="@+id/numberPicker1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical"
        max="100"
        min="1" />
    

有益なコメントをくれた MKJParekh に感謝します

于 2013-01-05T17:19:38.133 に答える