Tutorials  /  JavaScript

Mastering the Art of Dropdown Lists with Android Spinners

Ccentron Redaktion · September 2024 ·3 min read ·JavaScript, Tutorial

Dive into the world of Android development with our latest blog post focusing on the use of Spinners. Learn how to create interactive dropdown lists, transfer data between activities, and display toast notifications. An essential guide for developers looking to design elegant user interfaces!

What is an Android Spinner?

An Android Spinner is akin to a dropdown list, as seen in other programming languages like HTML. It allows users to select an option from a list. By default, the Spinner displays the currently selected value. Upon touching the Spinner, a dropdown menu containing all available values appears, from which the user can select a new one. The Spinner in Android is linked with AdapterView, thus we need to set the adapter class with the Spinner.

VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

Creating a Dropdown List

To create a Spinner in an Android application, we need an XML file defining the layout of the Spinner. In this XML file, the Spinner is created with a text label and the Spinner element itself.

Code
<!-- XML code for the layout of a simple Spinner -->
< LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    
    <!-- Text label -->
    < TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="Category:"
        android:layout_marginBottom="5dp"
    />
    
    <!-- Spinner element -->
    < Spinner 
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/spinner_title"
    />
< /LinearLayout>>

Using the Spinner in the Activity Class

In the activity class, we need to initialize the Spinner, assign it a list of options, and add a listener for selection changes. Here's a code snippet example of how this is done in the MainActivity:

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

    // Initialize Spinner element
    final Spinner spinner = (Spinner) findViewById(R.id.spinner);
    
    // Add Spinner listener
    spinner.setOnItemSelectedListener(this);

    // Set options for the Spinner
    List categories = new ArrayList();
    categories.add("Item 1");
    categories.add("Item 2");
    categories.add("Item 3");
    // Add more items...

    // Create adapter for the Spinner
    ArrayAdapter dataAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, categories);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // Connect adapter with the Spinner
    spinner.setAdapter(dataAdapter);
}

Data Transfer with Bundles and Toast Messages

After selecting an element from the Spinner, we want to pass the selection to another activity. For this purpose, we use Bundles. Additionally, we display a toast message with the selected option. The code for this could look like the following:

Code
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // Get selected item
    String item = parent.getItemAtPosition(position).toString();

    // Display toast message
    Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
    // If nothing is selected
}

// Method for button click to pass data to the next activity
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent= new Intent(MainActivity.this,SecondActivity.class);
        intent.putExtra("data",String.valueOf(spinner.getSelectedItem()));
        startActivity(intent);
    }
});

Conclusion

Utilizing a Spinner in Android applications allows developers to easily and effectively incorporate dropdown lists. By combining with Bundles, data can be transferred between activities, while toast messages provide feedback to the user about their selection. In this tutorial, we've gained a basic overview of using Spinners in Android applications and learned how to effectively utilize them.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren