Android NumberPicker:从 XML 设置最小值、最大值、默认值 [英] Android NumberPicker: Set min, max, default from XML

查看:11
本文介绍了Android NumberPicker:从 XML 设置最小值、最大值、默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法设置NumberPicker 来自 XML 布局?

Is there a way to set the minimum, maximum and default values of a NumberPicker from the XML Layout?

我是在活动代码中进行的:

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):

  1. 我创建了自己的 NumberPicker-Class

  1. 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

    这篇关于Android NumberPicker:从 XML 设置最小值、最大值、默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆