Friday, 12 June 2015

Spinner example Using JAVA programming in android

No comments
Hello friends,in this android tutorial we learn how to implement Spinner using java programming in android.In this example i write a very simple code to implement spinner.spinner is a nothing but  a like a drop down menu.

Let me explore example To create spinner using JAVA

CREATE NEW ANDROID PROJECT:

Step 1: Write code into activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Androidapplink"
        android:textSize="20sp" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Select Business Type"
        android:textSize="20sp" />

    <Spinner
        android:id="@+id/spBusinessType"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/businesstype" >
    </Spinner>

</LinearLayout>

Step 2: Write code into MainActivity.java

package dev.androidapplink.spinnerusingjava;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {

// Create variable
Spinner spBusinessType;

// Data Source
String businessType[] = { "electronics", "android", "designer", "Computers", "Education",
"Personal", "ios" , "web devloping"};

// Adapter
ArrayAdapter<String> adapterBusinessType;

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

// Initialize Spinner
spBusinessType = (Spinner) findViewById(R.id.spBusinessType);

// Initialize and set Adapter for spinner
adapterBusinessType = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, businessType);
spBusinessType.setAdapter(adapterBusinessType);

// create Item Selected Listener
spBusinessType.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
String item = adapter.getItemAtPosition(position).toString();

// Showing selected spinner item in a toast
Toast.makeText(getApplicationContext(),
"Bussiness Type : " + item, Toast.LENGTH_LONG).show();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
});
}

}

Step 3: Run Your Project:




No comments :

Post a Comment

Follow me Share