Spinner is the ordinary dropdown menu available for android. In this tutorial we are going to code a spinner using the arrayAdapter.
Java:
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MainActivity extends Activity implements
AdapterView.OnItemSelectedListener {
String itemValue;
Spinner spinnerOsversions;
public void addData() { }
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
ArrayList arrayList = new ArrayList();
arrayList.add("Item 1");
arrayList.add("Item 2");
arrayList.add("Item 3");
arrayList.add("Item 4");
arrayList.add("Item 5");
spinnerOsversions = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.simplerow,
arrayList);
arrayAdapter.setDropDownViewResource(R.layout.simplerow);
spinnerOsversions.setAdapter(arrayAdapter);
spinnerOsversions
.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this);
}
public void onItemSelected(AdapterView<?> adapterView, View view, int n,
long l) {
spinnerOsversions.setSelection(n);
String selectedItem = spinnerOsversions.getSelectedItem().toString();
Log.d("selected item ===", selectedItem);
}
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
XML:
simplerow.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10.0dip"
android:textSize="16.0sp" />
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="@id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
That's all, now run our app!
No comments:
Post a Comment