Wednesday, 21 January 2015

NumberPickerDialog Example

For Number Picker Dialog we require minimum API Level 11






Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Number Picker Dialog</string>
    <string name="button_name">Get Number</string>

</resources>

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <NumberPicker
        android:id="@+id/numberPicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="22dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/button_name" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:layout_marginLeft="33dp"
        android:layout_marginTop="32dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

MainActivity.java
package com.swamys.numberpickerdialog;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.TextView;

public class MainActivity extends Activity {
      
       NumberPicker numberPicker;
       TextView textView;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
             
              Button button = (Button) findViewById(R.id.button1);
              textView = (TextView) findViewById(R.id.textView1);
              numberPicker = (NumberPicker) findViewById(R.id.numberPicker1);
              numberPicker.setMaxValue(10);
              numberPicker.setMinValue(1);
              button.setOnClickListener(new OnClickListener() {
                    
                     @Override
                     public void onClick(View v) {
                           int selected_number = numberPicker.getValue();
                           textView.setText("Selected No. is: "+selected_number);
                     }
              });
       }
}



No comments:

Post a Comment