Android | Spinner Example

Two Files 1. SpinnerExample.java   2. spinner.xml

package myapplication.example1.com.hackonlycom;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class SpinnerExample extends Activity implements AdapterView.OnItemSelectedListener {

        String[] courses= {"Ethical Hacking", "Network Security", "Web Application Secuirty", "Exploit Writing", "Other"};

        @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.spinner);
        Spinner spin = findViewById(R.id.spinner);
        //spin.setOnItemClickListener((AdapterView.OnClickListener)this);       // spin.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this);spin.setOnItemSelectedListener(this);
            //Creating the ArrayAdapter instance having the country list            ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,courses);
            aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            //Setting the ArrayAdapter data on the Spinner            spin.setAdapter(aa);
        }

        //Performing action onItemSelected and onNothing selected

    public void onItemSelected(AdapterView arg0, View arg1, int position, long id) {
        Toast.makeText(getApplicationContext(),courses[position] , Toast.LENGTH_LONG).show();
    }

    public void onNothingSelected(AdapterView arg0) {
        // TODO Auto-generated method stub    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}


2. spinner.xml

xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">

    <Spinner        android:id="@+id/spinner"        android:layout_width="149dp"        android:layout_height="40dp"        android:layout_marginBottom="8dp"        android:layout_marginEnd="8dp"        android:layout_marginStart="8dp"        android:layout_marginTop="8dp"></Spinner>

</LinearLayout>
Reactions:

0 comments:

Post a Comment