Sunday, 27 January 2013

Spinner in Android

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"
    android:background="#ccffcc" >

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="50dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Display Selected item" />

</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:textSize="20dp" >

</TextView>

MainActivity.java:
package com.ram.spinnerview;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {
String[] names = { "name1", "name2", "name3", "name4", "name5", "Second Activity",
"name7", "name8", "name9", "name10" };

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

final Spinner spinner = (Spinner)findViewById(R.id.spinner1);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.text, names);
    spinner.setAdapter(adapter);
   
    Button b = (Button)findViewById(R.id.button1);
   
    b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {

int id = spinner.getSelectedItemPosition();

Toast.makeText(getApplicationContext(), names[id], 3000).show();
}
});
}
 

}


4 comments:

  1. Sir

    Where Text.xml file should create

    ReplyDelete
  2. create text.xml under layout folder only

    ReplyDelete
  3. create text.xml under layout folder.
    when the time your creating text xml choose root tag is textview

    ReplyDelete