我正在使用带有数字选择器的警报对话框,但是当我按下警报的“确定”按钮时,我不知道在活动中将te数字选择器值提供给textview的简单方法.
public class SecondActivity extends Activity {
public void button2 (View v){
View v1 = getLayoutInflater().inflate(R.layout.dialog1,null);
NumberPicker picker = (NumberPicker) v1.findViewById(R.id.np1);
picker.setMinValue(1);
picker.setMaxValue(20);
picker.setWrapSelectorWheel(false);
//final int number = picker.getValue();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView (v1);
builder.setTitle("Cantidad");
builder.setPositiveButton(android.R.string.ok,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
return;
} });
builder.setNegativeButton(android.R.string.cancel,int which) {
return;
} });
AlertDialog dialog = builder.create();
dialog.show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
显示布局:
活动布局:
最佳答案
使用picker.getValue()获取选择器的当前值.
选中“对话框”按钮后,使用选定的值更新“活动”中的TextView
builder.setPositiveButton(android.R.string.ok,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
int pickedValue = picker.getValue();
// set your TextView id instead of R.id.textView1
TextView textView = (TextView)findViewById(R.id.textView1);
textView.setText(Integer.toString(pickedValue));
return;
} });
您还可以添加侦听器来侦听这样的数字更改
picker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker,int oldVal,int newVal) {
// do your other stuff depends on the new value
}
});