web-dev-qa-db-fra.com

Comment créer une liste déroulante?

Comment créer une liste déroulante? J'ai essayé un ScrollView mais ce n'est pas exactement ce dont j'ai besoin.

179
user1820528

La meilleure façon de le faire est:

Aperçu:

enter image description here

XML:

<Spinner
    Android:id="@+id/spinner1"
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:background="@Android:drawable/btn_dropdown"
    Android:spinnerMode="dropdown"/>

Java:

//get the spinner from the xml.
Spinner dropdown = findViewById(R.id.spinner1);
//create a list of items for the spinner.
String[] items = new String[]{"1", "2", "three"};
//create an adapter to describe how the items are displayed, adapters are used in several places in Android.
//There are multiple variations of this, but this is the basic variant.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, Android.R.layout.simple_spinner_dropdown_item, items);
//set the spinners adapter to the previously created one.
dropdown.setAdapter(adapter);

Notes:

  1. Vous pouvez utiliser un setOnItemSelectedListener avec cela.
  2. Vous pouvez ajouter une liste de chaînes à partir de xml
  3. Il existe une version appCompat de cette vue.

Plus d'informations:

Ce sont les bases mais il y a plus à apprendre soi-même avec l'expérimentation.

https://developer.Android.com/guide/topics/ui/controls/spinner.html

251
Nicolas Tyler

Spinner xml:

<Spinner
      Android:id="@+id/spinner"
      Android:layout_width="wrap_content"
      Android:layout_height="match_parent" />

Java:

public class MainActivity extends Activity implements OnItemSelectedListener{

    private Spinner spinner;
    private static final String[] paths = {"item 1", "item 2", "item 3"};

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

        spinner = (Spinner)findViewById(R.id.spinner);
        ArrayAdapter<String>adapter = new ArrayAdapter<String>(MainActivity.this,
                Android.R.layout.simple_spinner_item,paths);

        adapter.setDropDownViewResource(Android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {

        switch (position) {
            case 0:
                // Whatever you want to happen when the first item gets selected
                break;
            case 1:
                // Whatever you want to happen when the second item gets selected
                break;
            case 2:
                // Whatever you want to happen when the thrid item gets selected
                break;

        }
    }

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

}
90
Jakob

enter image description here

Voici le code pour cela.

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" >

<Spinner
    Android:id="@+id/static_spinner"
    Android:layout_width="fill_parent"
    Android:layout_height="wrap_content"
    Android:layout_marginBottom="20dp"
    Android:layout_marginTop="20dp" />

<Spinner
    Android:id="@+id/dynamic_spinner"
    Android:layout_width="fill_parent"
    Android:layout_height="wrap_content" />

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Ahotbrew.com - Dropdown</string> 
<string-array name="brew_array">
    <item>Cappuccino</item>
    <item>Espresso</item>
    <item>Mocha</item>
    <item>Caffè Americano</item>
    <item>Cafe Zorro</item>
</string-array> 

Activité principale

Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);

    // Create an ArrayAdapter using the string array and a default spinner
    ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter
            .createFromResource(this, R.array.brew_array,
                    Android.R.layout.simple_spinner_item);

    // Specify the layout to use when the list of choices appears
    staticAdapter
            .setDropDownViewResource(Android.R.layout.simple_spinner_dropdown_item);

    // Apply the adapter to the spinner
    staticSpinner.setAdapter(staticAdapter);

    Spinner dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);

    String[] items = new String[] { "Chai Latte", "Green Tea", "Black Tea" };

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            Android.R.layout.simple_spinner_item, items);

    dynamicSpinner.setAdapter(adapter);

    dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {
            Log.v("item", (String) parent.getItemAtPosition(position));
        }

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

Cet exemple provient de http://www.ahotbrew.com/Android-dropdown-spinner-example/

48
Gurinder Singh

Ce code fonctionne très bien pour moi, j'espère qu'il vous aidera aussi.

item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="fill_parent"
    Android:layout_height="wrap_content"
    Android:orientation="vertical"
    Android:padding="1dip" >
    <TextView
        Android:id="@+id/spinnerItem"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:padding="2dp"
        Android:textSize="12sp" >
    </TextView>
</RelativeLayout>

details.xml

<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:orientation="vertical"
        Android:layout_marginBottom="20dp"
        Android:background="#FF00FF">   
    <Spinner
            Android:id="@+id/dropStatus"
            Android:layout_width="250dp"
            Android:layout_height="30dp"
            Android:layout_marginBottom="7dp"
            Android:drawSelectorOnTop="true"/> 
</LinearLayout>

Classe de l'adaptateur:

import Java.util.ArrayList;

import Android.content.Context;
import Android.content.res.Resources;
import Android.view.LayoutInflater;
import Android.view.View;
import Android.view.ViewGroup;
import Android.widget.ArrayAdapter;
import Android.widget.TextView;

public class StatusAdapter extends ArrayAdapter<StatusBean> {

    private Context context;
    private ArrayList<StatusBean> statuses;
    public Resources res;
    StatusBean currRowVal = null;
    LayoutInflater inflater;

    public StatusAdapter(Context context,
            int textViewResourceId, ArrayList<StatusBean> statuses,
            Resources resLocal) {
        super(context, textViewResourceId, statuses);
        this.context = context;
        this.statuses = statuses;
        this.res = resLocal;        
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {
        View row = inflater.inflate(R.layout.status_item, parent, false);
        currRowVal = null;
        currRowVal = (StatusBean) statuses.get(position);
        TextView label = (TextView) row.findViewById(R.id.spinnerItem);
        if (position == 0) {
            label.setText("Please select status");
        } else {
            label.setText(currRowVal.getStatus());
        }

        return row;
    }
}

Classe StatusBean:

public class StatusBean {

    private String status;
    private String statusCode;

    public StatusBean() {
    }

    public StatusBean(String status,
            String statusCode) {
        this.status = status;
        this.statusCode = statusCode;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status =  status;
    }

    public String getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(String statusCode) {
        this.statusCode = statusCode;
    }
}

Classe d'activité:

À l'intérieur onCreate methos:

static ArrayList<StatusBean> STATUS_LIST = new ArrayList<StatusBean>();

for(int i=0;i<=10;i++) {
STATUS_LIST.add(new StatusBean(“Status ”+i, “Stattus ”+i));
}

final Spinner  dropStatus = (Spinner)findViewById(R.id.dropStatus);
            Resources res = getResources(); 
            StatusAdapter adapter = new StatusAdapter(this, R.layout.item, SessionData. STATUS_LIST, res);
            dropStatus.setAdapter(adapter);
12
Md. Kamruzzaman

Vous avez besoin d'un Spinner. Voici un exemple:

spinner_1 = (Spinner) findViewById(R.id.spinner1);
    spinner_1.setOnItemSelectedListener(this);
    List<String> list = new ArrayList<String>(); 
    list.add("RANJITH");
    list.add("ARUN");
    list.add("JEESMON");
    list.add("NISAM");
    list.add("SREEJITH");
    list.add("SANJAY");
    list.add("AKSHY");
    list.add("FIROZ");
    list.add("RAHUL");
    list.add("ARJUN");
    list.add("SAVIYO");
    list.add("VISHNU");

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, Android.R.layout.simple_spinner_item, list);
    adapter.setDropDownViewResource(Android.R.layout.simple_spinner_dropdown_item);
    spinner_1.setAdapter(adapter);


    spinner_2 = (Spinner) findViewById(R.id.spinner_two);
    spinner_2.setOnItemSelectedListener(this);
    List<String> city = new ArrayList<String>();
    city.add("KASARGOD");
    city.add("KANNUR");
    city.add("THRISSUR");
    city.add("KOZHIKODE");
    city.add("TRIVANDRUM");
    city.add("ERNAMKULLAM");
    city.add("WAYANAD");
    city.add("PALAKKAD");
    city.add("ALAPUZHA");
    city.add("IDUKKI");
    city.add("KOTTAYAM");
    city.add("PATHANAMTHITTA");
    city.add("KOLLAM");
    city.add("MALAPPURAM");
    ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, Android.R.layout.simple_spinner_item, city);
    adapter2.setDropDownViewResource(Android.R.layout.simple_spinner_dropdown_item);
    spinner_2.setAdapter(adapter2);



@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
        long id) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "YOUR SELECTION IS : " + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();


}

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

}
10

Vous pouvez également utiliser le widget AppCompatSpinner:

<Android.support.v7.widget.AppCompatSpinner
    Android:id="@+id/spinner_order_type"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    app:backgroundTint="@color/red"/>

Dans votre classe d'activité:

AppCompatSpinner spinOrderType = (AppCompatSpinner) findViewById(R.id.spinner_order_type);
List<String> categories = new ArrayList<String>();
        categories.add(getString(R.string.label_table_order));
        categories.add(getString(R.string.label_take_away));

        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(mContext,
                R.layout.layout_spinner_item, categories);
        dataAdapter.setDropDownViewResource(R.layout.layout_spinner_item);
        spinOrderType.setAdapter(dataAdapter);
        spinOrderType.setSelection(0);

        spinOrderType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
                String item = parent.getItemAtPosition(position).toString();
                Log.d(TAG, item);
            }

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

            }
        });

layout_spinner_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    xmlns:tools="http://schemas.Android.com/tools"
    Android:gravity="left"
    Android:textSize="@dimen/text.size.large"
    Android:textColor="@color/text.link"
    Android:padding="@dimen/margin.3" />
6
Md Imran Choudhury

Essaye ça...

<string-array name="names">

        <item></item>
        <item>By Bus</item>
        <item>By Train</item>
        <item>By Van</item>
        <item>By Bike</item>
    </string-array>


String travel_type;


ArrayAdapter<String> myAdapter = new ArrayAdapter(AddNew_Trip.this,Android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.names)); 
        myAdapter.setDropDownViewResource(Android.R.layout.simple_dropdown_item_1line); 
        mySpinner.setAdapter(myAdapter); 

        mySpinner.setOnItemSelectedListener( 
                new AdapterView.OnItemSelectedListener() { 

                    @Override 
                    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
                        travel_type = String.valueOf(adapterView.getItemAtPosition(i)); 
                        //Toast.makeText(Plan_Trip.this, travel_type, Toast.LENGTH_SHORT).show(); 
                    } 

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

                    } 

                } 
        ); 
    }
4
yasith nawanjana

Essaye ça:

package example.spin.spinnerexample;

import Android.support.v7.app.AppCompatActivity;
import Android.os.Bundle;
import Android.view.View;
import Android.widget.AdapterView;
import Android.widget.ArrayAdapter;
import Android.widget.Spinner;
import Android.widget.Toast;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{

    String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Getting the instance of Spinner and applying OnItemSelectedListener on it
        Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
        spin.setOnItemSelectedListener(this);

        //Creating the ArrayAdapter instance having the bank name list
        ArrayAdapter aa = new ArrayAdapter(this,Android.R.layout.simple_spinner_item,bankNames);
        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
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
        Toast.makeText(getApplicationContext(), bankNames[position], Toast.LENGTH_LONG).show();
    }

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

    }
}

activity_main.xml: -

<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:tools="http://schemas.Android.com/tools"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    Android:paddingBottom="@dimen/activity_vertical_margin"
    Android:paddingLeft="@dimen/activity_horizontal_margin"
    Android:paddingRight="@dimen/activity_horizontal_margin"
    Android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Spinner
        Android:id="@+id/simpleSpinner"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_centerHorizontal="true"
        Android:layout_marginTop="100dp" />

</RelativeLayout>
1
Sriram