有没有一种方法来设置的从XML布局NumberPicker ?
Is there a way to set the minimum, maximum and default values of a NumberPicker from the XML Layout?
我是从内活动code做的:
I'm doing it from within the Activity code:
np = (NumberPicker) findViewById(R.id.np);
np.setMaxValue(120);
np.setMinValue(0);
np.setValue(30);
XML显然是比较合适的,因为它定义属性,而不是行为。
XML is obviously more appropriate , because it defines property, not behaviour.
有没有一种方法使用XML布局设置这些?
Is there a way to set these using the XML layout?
我有同样的问题,这是我如何解决它(根据MKJParekh的注释):
I had the same problem, this is how I solved it (according to the comment of MKJParekh):
我创造了我自己的NumberPicker级
I created my own 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));
}
}
现在,你可以在你的XML布局文件中使用此NumberPicker
Now you can use this NumberPicker in your xml layout file
<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对他有用的注释
Thanks to MKJParekh for his useful comment