小智 7
Android为此提供了内置小部件数字选择器。
数字选择器示例
活动主文件
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity"
android:background="#ffffff"
>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:text="Select a Language..."
/>
<NumberPicker
android:id="@+id/np"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv"
/>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
MainActivity.java
import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
import android.widget.NumberPicker;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get the widgets reference from XML layout
final TextView tv = (TextView) findViewById(R.id.tv);
NumberPicker np = (NumberPicker) findViewById(R.id.np);
//Set TextView text color
tv.setTextColor(Color.parseColor("#FF2C834F"));
//Initializing a new string array with elements
final String[] values= {"English","Hindi", "Suomi"};
//Populate NumberPicker values from String array values
//Set the minimum value of NumberPicker
np.setMinValue(0); //from array first value
//Specify the maximum value/number of NumberPicker
np.setMaxValue(values.length-1); //to array last value
//Specify the NumberPicker data source as array elements
np.setDisplayedValues(values);
//Gets whether the selector wheel wraps when reaching the min/max value.
np.setWrapSelectorWheel(true);
//Set a value change listener for NumberPicker
np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal){
//Display the newly selected value from picker
tv.setText("Selected value : " + values[newVal]);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9959 次 |
| 最近记录: |