Android-多个NumberPicker值由外部总值限制
创始人
2024-08-19 18:00:09
0

使用NumberPicker的OnValueChangeListener接口来监测NumberPicker值的变化。在每次值变化时,更新其他NumberPicker的最大值和最小值,以确保它们的总和始终等于预设的总值。以下是一个示例实现:

public class MainActivity extends AppCompatActivity implements NumberPicker.OnValueChangeListener {
    private NumberPicker np1, np2, np3;
    private int totalValue = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        np1 = findViewById(R.id.np1);
        np2 = findViewById(R.id.np2);
        np3 = findViewById(R.id.np3);

        np1.setOnValueChangedListener(this);
        np2.setOnValueChangedListener(this);
        np3.setOnValueChangedListener(this);

        np1.setMaxValue(totalValue);
        np2.setMaxValue(totalValue - np1.getValue());
        np3.setMaxValue(totalValue - np1.getValue() - np2.getValue());
    }

    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        int newTotal = newVal + np2.getValue() + np3.getValue();
        int diff = totalValue - newTotal;

        if (diff < 0) {
            // The new value exceeds the total.
            picker.setValue(oldVal);
            return;
        }

        // Update the maximum values of the other NumberPickers.
        switch (picker.getId()) {
            case R.id.np1:
                np2.setMaxValue(diff);
                np3.setMaxValue(totalValue - newVal - np2.getValue());
                break;
            case R.id.np2:
                np1.setMaxValue(diff + newVal);
                np3.setMaxValue(totalValue - np1.getValue() - newVal);
                break;
            case R.id.np3:
                np1.setMaxValue(diff + newVal + np2.getValue());
                np2.setMaxValue(totalValue - np1.getValue() - newVal);
                break;
        }
    }
}

相关内容

热门资讯

详细辅助!闲逸碰胡外桂,火神大... 详细辅助!闲逸碰胡外桂,火神大厅辅助,透视实锤开挂(有挂方略) >>您好:软件加薇136704302...
了解辅助!新西部大厅辅助,老友... 了解辅助!新西部大厅辅助,老友广东辅助工具下载地址,科技介绍开挂(有人有挂)>>您好:软件加薇136...
科技辅助!财神十三章怎样加强运... 科技辅助!财神十三章怎样加强运气,哈糖大菠萝提高胜率,透视安装开挂(有挂解惑) 了解更多开挂安装加(...
原来有辅助!玉海楼茶苑辅助器,... 原来有辅助!玉海楼茶苑辅助器,皇豪互众辅助软件是干嘛的,我来分享开挂(详细教程)《详细加薇13670...
传授辅助!雀姬手机辅助脚本,兴... 传授辅助!雀姬手机辅助脚本,兴动互娱辅助工具,玩家必看科普开挂(有挂攻略);亲,兴动互娱辅助工具这款...
分析辅助!途游休闲铺破解版,越... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
实测辅助!关春天跑得快辅助器,... 实测辅助!关春天跑得快辅助器,创思维激k辅助器视频,玩家必备攻略开挂(有挂助手)>>您好:软件加13...
通报辅助!越乡游义乌辅助工具,... 大家好,今天小编来为大家解答越乡游义乌辅助工具这个问题咨询软件客服可以免费测试直接加微信(13670...
推荐辅助!快乐碰胡辅助,心悦踢... 推荐辅助!快乐碰胡辅助,心悦踢辅助软件,一分钟教会你开挂(有挂教程)1、下载安装好心悦踢辅助软件,进...
分析辅助!江西中至黑科技辅助插... 分析辅助!江西中至黑科技辅助插件,拱趴游戏插件,每日必看推荐开挂(真是有挂)>>您好:软件加1367...