How to create Spinner in Android:
Spinner : A view that displays one child at a time and
lets the user pick among them. The items in the Spinner come from the Adapter associated with this view. Android Spinner help user to select an item from
desired items. It’s like drop down in html.
Here is a code needed to implement Spinner :
MainActivity.java
public class MainActivity extends Activity {
Spinner
spinner;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner)
findViewById(R.id.spinner1);
final String[] arr = {"Java" ,"Android", "C", "C++"};
ArrayAdapter<String>
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,arr);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new
OnItemSelectedListener() {
@Override
public void
onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(MainActivity.this, "You have
chosen "+arr[arg2], Toast.LENGTH_SHORT).show();
}
@Override
public void
onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated
method stub
}
});
}
@Override
public boolean
onCreateOptionsMenu(Menu menu) {
// Inflate the
menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp" />
</RelativeLayout>
Reach us At: - 0120-4029000 / 24 / 25 / 27 / 29 Mbl: 9953584548
No comments:
Post a Comment