在 android 中使用数字选择器添加或减去 TextView 的整数值



我有两个数字选择器,例如:阅读数字选择器和诗歌数字选择器,默认情况下每个学生获得 10 分,每次学生犯错时,数字选择器都会增加,分数应该减少 (0.5( 分,下面给出的示例代码,请帮助如何实现此特定方法。两个数字选择器都有递增和递减方法,两个数字选择器都应添加或减去相同的 textView,默认值为 10。

public class MainActivity extends AppCompatActivity {
private NumberPicker readingPicker;
private NumberPicker poempicker;
private TextView pointsTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readingPicker = findViewById(R.id.reading_picker);
poempicker = findViewById(R.id.poem_picker);
// increase or decrease value of points text view (10 default) using below number pickers.
pointsTextView = findViewById(R.id.ten_points);
readingPicker.setValueChangedListener(new ValueChangedListener() {
@Override
public void valueChanged(int value, ActionEnum action) {
switch (action){
case INCREMENT:
// TODO: decrease value of pointsTextView by 0.5
break;
case DECREMENT:
// TODO: increase value of pointsTextView by 0.5
}
}
});
// after getting the value from above reading picker
poempicker.setValueChangedListener(new ValueChangedListener() {
@Override
public void valueChanged(int value, ActionEnum action) {
switch (action) {
case INCREMENT:
// TODO: decrease value of same pointsTextView by 0.5
break;
case DECREMENT:
// TODO: increase value of same pointsTextView by 0.5
}

}
});
}
}

我能够使用阅读数字选择器进行减法,但在那之后,我对如何获取文本视图的当前值并使用第二个数字选择器进一步减去有点困惑。

readingPicker.setValueChangedListener(new ValueChangedListener() {
@Override
public void valueChanged(int value, ActionEnum action) {
switch (action) {
case INCREMENT:
double currentValue = Double.parseDouble(pointsTextView.getText().toString());
currentValue = currentValue + 0.5;
pointsTextView.setText(String.valueOf(currentValue));
break;
case DECREMENT:
double currentValue1 = Double.parseDouble(pointsTextView.getText().toString());
currentValue1 = currentValue1 - 0.5;
pointsTextView.setText(String.valueOf(currentValue1));
}
}
});

这样您就可以达到预期的结果。获取pointsTextView的当前值,然后对其执行加法或减法运算,然后再次将该值设置为pointsTextView

最新更新