Wednesday, 4 September 2013

Number Picker Dialog


A widget that enables the user to select a number form a predefined range. There are two flavors of this widget and which one is presented to the user depends on the current theme.

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"  
  >  
   <NumberPicker  
     android:id="@+id/numberPicker1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentLeft="true"  
     android:layout_alignParentTop="true"  
     android:layout_marginLeft="78dp" />  
   <Button  
     android:id="@+id/button1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentLeft="true"  
     android:layout_centerVertical="true"  
     android:layout_marginLeft="40dp"  
     android:text="Show Selected Number" />  
 </RelativeLayout>  

MainActivity.java:

 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.Toast;  
 public class MainActivity extends Activity {  
  NumberPicker np;  
  @Override  
  protected void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);  
  setContentView(R.layout.activity_main);  
  np = (NumberPicker) findViewById(R.id.numberPicker1);  
  np.setMaxValue(10);  
  np.setMinValue(1);  
  Button b = (Button) findViewById(R.id.button1);  
  b.setOnClickListener(new OnClickListener() {  
   @Override  
   public void onClick(View arg0) {  
   // TODO Auto-generated method stub  
   int number = np.getValue();  
   Toast.makeText(getApplicationContext(),  
    "value is :" + number, 3000).show();  
   }  
  });  
  }  
 }  

Output:





Happy coding....:)

No comments:

Post a Comment