Saturday, 18 April 2020

ANDROID STUDIO Drop Down List Tutorial

THIS CODE IS USED IN SAEEDISOFT YOUTUBE CHANNEL VIDEO FOR SHOWING DROP DOWN LIST IN ANDROID APP 


XML FILE CODE



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="350dp"
        android:layout_height="wrap_content"

        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>



JAVA CODE : 


package com.saeedisoft.codetesting;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
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 java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    Spinner spinner;
    Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        spinner = findViewById(R.id.spinner);

        loadDropDownValues();


        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    Toast.makeText(mContext, "Pakistan", Toast.LENGTH_SHORT).show();
                } else if (position == 1) {
                    Toast.makeText(mContext, "Afghanistan", Toast.LENGTH_SHORT).show();
                } else if (position == 2) {
                    Toast.makeText(mContext, "Iran", Toast.LENGTH_SHORT).show();
                } else if (position == 3) {
                    Toast.makeText(mContext, "India", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void loadDropDownValues() {
        List<String> countries = new ArrayList<>();
        countries.add("PAKISTAN");
        countries.add("AFGHANISTAN");
        countries.add("IRAN");
        countries.add("INDIA");

        ArrayAdapter adapter = new ArrayAdapter(mContext, android.R.layout.simple_spinner_dropdown_item, countries);
        spinner.setAdapter(adapter);
    }
}

No comments:

Post a Comment