ScreenShots:
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="55dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="ShowSelectedMonth" />
</LinearLayout>
text.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ff00ff"
android:textSize="20dp" >
</TextView>
MainActivity.java:
package com.ram.spinnerdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Spinner spinner = (Spinner) findViewById(R.id.spinner1);
Button showBtn = (Button) findViewById(R.id.button1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getApplicationContext(), R.layout.text, MONTHS);
spinner.setAdapter(adapter);
// cannot use this interface for spinner
// spinner.setOnItemClickListener(this);
spinner.setOnItemSelectedListener(this);
showBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position = spinner.getSelectedItemPosition();
Toast.makeText(getApplicationContext(),
"selected month is :" + MONTHS[position],
Toast.LENGTH_SHORT).show();
}
});
}
String[] MONTHS = { "jan", "feb", "mar", "april", "may", "june", "july",
"aug", "sep", "oct", "nov", "dec" };
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"selected month is :" + MONTHS[arg2], Toast.LENGTH_SHORT)
.show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
No comments:
Post a Comment