click here to download source code
package name : selva.spinner
project name : Spinner
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="114dp"
android:text="Spinner"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#00ff00" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="50dp"
android:text="Select Country"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ffffff" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="100dp"
>
</Spinner>
</RelativeLayout>
strings.xml
(res --> values --> strings.xml)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, SpinnerActivity!</string>
<string name="app_name">Spinner</string>
<string name="country">Choose a country</string>
<string-array name="country">
<item>United States</item>
<item>india</item>
<item>France</item>
<item>Germany</item>
<item>Denmark</item>
<item>South Korea</item>
<item>England</item>
<item>South Africa</item>
</string-array>
</resources>
SpinnerActivity.java
package selva.spinner;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner sp = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.country, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext(), "The country is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
OUTPUT:
select spinner
select country
click here to download source code
No comments:
Post a Comment