activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/chooselow"/>
<NumberPicker
android:id="@+id/numberPicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/choosehigh"/>
<NumberPicker
android:id="@+id/numberPicker2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</TableRow>
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">NumberPicker</string>
<string name="action_settings">Settings</string>
<string name="chooselow">選擇低價</string>
<string name="choosehigh">選擇高價</string>
</resources>
MainActivity.java
package com.lxm.numberpicker;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity {
NumberPicker numberPicker;
int minPrice = 20;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numberPicker = (NumberPicker) findViewById(R.id.numberPicker);
numberPicker.setMinValue(20);
numberPicker.setMaxValue(100);
numberPicker.setValue(minPrice);
numberPicker.setOnValueChangedListener(new OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
minPrice = newVal;
showSelectedPrice();
}
});
}
private void showSelectedPrice() {
Toast.makeText(this, "你選擇的最低價格是"+minPrice, Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
运行结果: