Friday, 25 October 2013

Simple Spinner with Dynamic Data

Hi!


   Some time we may facing problem to load the dynamic data on android spinners.

I give you a very simple way to load the spinner with dynamic data by using normal ArrayAdapter<String>.

Create a Spinner on your xml file


  • For Static Data:



if you wants using static data you can use the  android:entries
and cal the array data from your string.xml like,


<string-array name="project">
Select
<item>Project_100</item>
<item>Project_101</item>
    </string-array>



<Spinner
            android:id="@+id/spinner1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:entries="@array/project" />


  • For Dynamic Data:



if you wants to load the data dynamically fallow the code below,

Call the spinner normally in your xml


<Spinner
            android:id="@+id/spinner2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />




  1. In your Activity class declare an ArrayAdapter<String> for custom spinner,
  2. Create a List<String> for keep your date as list,
  3. Set the List on your ArrayAdapter<String>,
  4. set the Adapter on your Spinner
package dcs.raj.timesheet;

import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.app.Activity;

public class EditTimeSheet extends Activity {

Spinner pjt_spnr;
ArrayAdapter<String> pjt_sp_adoptr;
List<String> pjt_sp_list;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_time_sheet);

pjt_sp_list = new ArrayList<String>();
pjt_sp_list.add("Project_1");
pjt_sp_list.add("Project_2");
pjt_sp_list.add("Project_3");
pjt_sp_list.add("Project_4");
pjt_sp_list.add("Project_5");
pjt_spnr = (Spinner) findViewById(R.id.spinner2);
pjt_sp_adoptr = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item, pjt_sp_list);
pjt_sp_adoptr
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
pjt_spnr.setAdapter(pjt_sp_adoptr);
}

}

Thats All..,

Thank You!


Please Leave Your Comment..,




No comments:

Post a Comment