Spinner dinámico en Android

Muchas veces en las aplicaciones de Android tenemos que crear cualquier vista dinámicamente sin escribir ningún código XML. Para eso, podemos crear nuestra vista usando nuestro archivo Kotlin o Java. En este artículo, veremos cómo crear dinámicamente una ruleta en una aplicación de Android. A continuación se muestra un video de muestra para tener una idea de lo que vamos a hacer en este artículo.

Nota : este artículo de Android cubre los lenguajes Java y Kotlin

Implementación paso a paso

Paso 1: crea un nuevo proyecto en Android Studio

Para crear un nuevo proyecto en Android Studio, consulte Cómo crear/iniciar un nuevo proyecto en Android Studio .

Paso 2: trabajar con el archivo activity_main.xml

Vaya a aplicación > res > diseño > actividad_principal.xml y agregue el código a continuación. Se agregan comentarios en el código para conocer en detalle. 

XML

<?xml version="1.0" encoding="utf-8"?>
<!--on below line we are creating our linear layout-->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/idLLContainer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">
</LinearLayout>

Paso 3: trabajar con el archivo MainActivity 

Vaya a aplicación > java > nombre del paquete de su aplicación > archivo MainActivity y agréguele el siguiente código. Se agregan comentarios en el código para conocer en detalle. 

Kotlin

package com.gtappdevelopers.kotlingfgproject
 
import android.graphics.Typeface
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.setPadding
 
class MainActivity : AppCompatActivity() {
 
    // on below line we are creating a variable.
    lateinit var languagesList: List<String>
    lateinit var containerLL: LinearLayout
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // on below line we are initializing our variables
        languagesList = ArrayList()
        containerLL = findViewById(R.id.idLLContainer)
 
        // on below line we are adding languages
        // to our language list
        languagesList = languagesList + "Java"
        languagesList = languagesList + "Kotlin"
        languagesList = languagesList + "C++"
        languagesList = languagesList + "C"
 
        // on below line we are creating layout
        // params for text view.
        // and specifying width as match parent
        // and height as wrap content
        val txtLayoutParam = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        // on below line we are adding gravity
        txtLayoutParam.gravity = Gravity.CENTER
 
        // on below line we are creating layout params for spinner.
        // and specifying width as wrap parent and height as wrap content
        val spinnerLayoutParam = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
 
        // on below line we are adding gravity
        spinnerLayoutParam.gravity = Gravity.CENTER
 
        // on below line we are creating our dynamic text view
        val headingTV = TextView(this)
         
        // on the below line we are setting for our text view.
        headingTV.text = "Dynamic Spinner in Android"
         
        // on below line we are updating text size.
        headingTV.textSize = 20f
         
        // on below line we are updating text color and font
        headingTV.setTextColor(resources.getColor(R.color.black))
        headingTV.typeface = Typeface.DEFAULT_BOLD
         
        // on below line we are adding padding
        headingTV.setPadding(20)
         
        // on below line we are specifying text alignment.
        headingTV.textAlignment = TextView.TEXT_ALIGNMENT_CENTER
         
        // on below line we are adding layout
        // param for heading text view.
        headingTV.layoutParams = txtLayoutParam
 
 
        //create spinner programmatically
        val spinner = Spinner(this)
 
        // on below line we are adding params for spinner.
        spinner.layoutParams = spinnerLayoutParam
 
        // on below line we are adding our views
        // to container linear layout
        containerLL.addView(headingTV)
        containerLL.addView(spinner)
 
        // on below line we are checking
        // if spinner is not null
        if (spinner != null) {
 
            // on below line we are initializing
            // and setting our adapter
            // to our spinner.
            val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, languagesList)
            spinner.adapter = adapter
 
            // on below line we are adding on item selected listener for spinner.
            spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>,
                    view: View, position: Int, id: Long
                ) {
                    // in on selected listener we are displaying a toast message
                    Toast.makeText(
                        this@MainActivity,
                        "Selected Language is : " +
                                "" + languagesList[position], Toast.LENGTH_SHORT
                    ).show()
                }
 
                override fun onNothingSelected(parent: AdapterView<*>) {
                }
            }
        }
    }
}

Java

package com.gtappdevelopers.kotlingfgproject;
 
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
 
public class MainActivity extends AppCompatActivity {
 
    // on below line we are creating variables.
    private LinearLayout containerLL;
    private ArrayList<String> languageList;
 
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // on below line we are initializing our variables.
        containerLL = findViewById(R.id.idLLContainer);
        languageList = new ArrayList<>();
 
        // on below line we are adding
        // languages to our language list
        languageList.add("Java");
        languageList.add("Kotlin");
        languageList.add("C++");
        languageList.add("C");
 
        // on below line we are creating layout params for text view.
        // and specifying width as match parent and height as wrap content
        LinearLayout.LayoutParams txtLayoutParam = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        // on below line we are adding gravity
        txtLayoutParam.gravity = Gravity.CENTER;
 
        // on below line we are creating layout params for spinner.
        // and specifying width as wrap parent and height as wrap content
        LinearLayout.LayoutParams spinnerLayoutParam = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        // on below line we are adding gravity
        spinnerLayoutParam.gravity = Gravity.CENTER;
 
        // on below line we are creating our dynamic text view
        TextView headingTV = new TextView(this);
        
        // on below line we are setting  for our text view.
        headingTV.setText("Dynamic Spinner in Android");
         
        // on below line we are updating text size.
        headingTV.setTextSize(20f);
         
        // on below line we are updating text color and font
        headingTV.setTextColor(getResources().getColor(R.color.black));
        headingTV.setTypeface(Typeface.DEFAULT_BOLD);
         
        // on below line we are adding padding
        headingTV.setPadding(20, 20, 20, 20);
         
        // on below line we are specifying text alignment.
        headingTV.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
         
        // on below line we are adding layout param
        // for heading text view.
        headingTV.setLayoutParams(txtLayoutParam);
 
        // create spinner programmatically
        Spinner spinner = new Spinner(this);
         
        // on below line we are adding params for spinner.
        spinner.setLayoutParams(spinnerLayoutParam);
 
        // on below line we are adding our
        // views to container linear layout
        containerLL.addView(headingTV);
        containerLL.addView(spinner);
 
        // on below line we are checking if spinner is not null
        if (spinner != null) {
            // on below line we are initializing and setting our adapter
            // to our spinner.
            ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, languageList);
            spinner.setAdapter(adapter);
            // on below line we are adding on item selected listener for spinner.
            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    // in on selected listener we are displaying a toast message
                    Toast.makeText(MainActivity.this, "Selected Language is : " + languageList.get(position), Toast.LENGTH_SHORT).show();
                }
 
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
 
                }
            });
        }
    }
}

Ahora ejecute su aplicación para ver el resultado. 

Producción:

Publicación traducida automáticamente

Artículo escrito por chaitanyamunje y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *