Using CardView as Beautiful Spinner Or DropDown in Android - SpartaCode

SpartaCode

Make your development faster and easier !

Using CardView as Beautiful Spinner Or DropDown in Android

Note :   Before getting started you must setup CardView into your Android Studio.
            Please check out my tutorial which shows how to setup Cardview.

Setup CardView


So lets get started,

Step 1 : Copy Paste following code into your XML layout file.

<android.support.v7.widget.CardView
           android:id="@+id/yourcardid"
           android:layout_width="wrap_content"
           android:layout_height="40dp"
           android:elevation="1dp"
           app:cardCornerRadius="20dp"
           android:innerRadius="0dp"
           android:shape="ring"
           android:thicknessRatio="1.9"
                        >
                        <Spinner
                            android:id="@+id/spinner_services"
                            android:layout_width="wrap_content"
                            android:layout_height="match_parent"
                            android:paddingLeft="10dp"
                            />
</android.support.v7.widget.CardView>


Step 2 : Go to corresponding Java file and add following code 

Declaration Code :

Spinner spinner;
List<String> list  = new ArrayList<>();
ArrayAdapter<String> spinnerAdapter;

Copy this code in onCreate() of your Activity :

//Define spinner
spinner=(Spinner) findViewById(R.id.spinner_services);
spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, android.R.id.text1);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);

Applying Listener on Spinner :

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        int selectedPosition= position;
    }
   
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
   
    }
});


Step 3: Add items into Spinner for options.

Adding items to list :

list.add("Sparta");
list.add("Coder");
list.add("Healthy");
list.add("Android");
list.add("Developer");

Adding list to Adapter and Notify Spinner to change its content :

spinnerAdapter.addAll(list);
spinnerAdapter.notifyDataSetChanged();



Thank you
Please visit again.

2 comments:

  1. How can we predefine the text on spinner, such as "select Items"?

    ReplyDelete
    Replies
    1. Please check out this link to set default value

      http://stackoverflow.com/questions/17063611/show-default-value-in-spinner-in-android

      Delete

Get Amazing Traffic to your Site

Traffic Exchange

Post Bottom Ad

Responsive Ads Here