如何创建下拉列表?

Posted

技术标签:

【中文标题】如何创建下拉列表?【英文标题】:How to create a drop-down list? 【发布时间】:2012-11-02 20:42:29 【问题描述】:

我已经尝试过 ScrollView,但这并不是我所需要的。

【问题讨论】:

好像你在找Spinner 您的问题的可能答案:***.com/a/39678401/5875797 【参考方案1】:

微调器 xml:

<Spinner
      android:id="@+id/spinner"
      android:layout_
      android:layout_ />

java:

public class MainActivity extends AppCompatActivity implements AdapterView.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
        


【讨论】:

我想调用 Multiple value 代替 private static final String[]paths = "item 1", "item 2", "item 3";帮助 php 代码从我的 sql 中获取数据我如何从 mysql 服务器中获取这些值并制作动态和管理员可更新的微调器【参考方案2】:

简单/优雅/我是怎么做的:

预览:

XML:

<Spinner
    android:id="@+id/spinner1"
    android:layout_
    android:layout_
    android:background="@android:drawable/btn_dropdown"
    android:spinnerMode="dropdown"/>

spinnerMode 设置为 dropdown 是 androids 制作下拉菜单的方式。 (https://developer.android.com/reference/android/widget/Spinner#attr_android:spinnerMode)

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);

文档:

这是基础知识,但还有更多内容需要通过实验自学。 https://developer.android.com/guide/topics/ui/controls/spinner.html

    您可以使用 setOnItemSelectedListener。 (https://developer.android.com/guide/topics/ui/controls/spinner.html#SelectListener) 您可以从 xml 添加字符串列表。 (https://developer.android.com/guide/topics/ui/controls/spinner.html#Populate) 此视图有一个 appCompat 版本。 (https://developer.android.com/reference/androidx/appcompat/widget/AppCompatSpinner)

【讨论】:

Tayler 您正在使用带有静态值的String array,如果数据来自web service 进入spinner(下拉)会怎样?我们应该怎么做? 以同样的方式,事实上我在我的应用程序上也是这样做的。创建微调器,从服务中获取数组,将数组添加到适配器,将适配器添加到微调器。 @MartinezToni this 在此示例中指的是活动。但是是的,您确实需要将有效的 Context 对象传递给该参数。 您使用的背景可绘制对象现已过时 @AlbertoM 它没有过时,它是可选的。如果您不想,也不需要使用默认背景。但是你可以...【参考方案3】:

这段代码对我来说很好,希望它对你也有帮助。

item.xml

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

details.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_
        android:layout_
        android:orientation="vertical"
        android:layout_marginBottom="20dp"
        android:background="#FF00FF">   
    <Spinner
            android:id="@+id/dropStatus"
            android:layout_
            android:layout_
            android:layout_marginBottom="7dp"
            android:drawSelectorOnTop="true"/> 
</LinearLayout>

适配器类:

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;
    

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;
    

活动类:

onCreate 方法内部:

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);

【讨论】:

【参考方案4】:

这是它的代码。

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:orientation="vertical" >

<Spinner
    android:id="@+id/static_spinner"
    android:layout_
    android:layout_
    android:layout_marginBottom="20dp"
    android:layout_marginTop="20dp" />

<Spinner
    android:id="@+id/dynamic_spinner"
    android:layout_
    android:layout_ />

字符串.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> 

主活动

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
        
    );

这个例子来自 http://www.ahotbrew.com/android-dropdown-spinner-example/

【讨论】:

【参考方案5】:

您需要Spinner。这是一个例子:

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


【讨论】:

【参考方案6】:

您也可以使用 AppCompatSpinner 小部件:

<android.support.v7.widget.AppCompatSpinner
    android:id="@+id/spinner_order_type"
    android:layout_
    android:layout_
    app:backgroundTint="@color/red"/>

在您的 Activity 类中:

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_
    android:layout_
    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" />

【讨论】:

Using Spinner widget in the XML alias' to AppCompatSpinner, 和android.support.v7.widget.AppCompatSpinner/>没有区别来自:developer.android.com/reference/android/support/v7/widget/…"这会自动在布局中使用 Spinner 时使用。编写自定义视图时只需要手动使用此类。"【参考方案7】:

试试这个...

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

                     

                 
        ); 
    

【讨论】:

【参考方案8】:

试试这个:

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_
    android:layout_
    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_
        android:layout_
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp" />

</RelativeLayout>

【讨论】:

您能否编辑这篇文章并解释这段代码如何回答这个问题?【参考方案9】:

在 Kotlin 中你可以这样做:

首先,将此代码放入您的布局中

   <Spinner
            android:id="@+id/spinner"
            android:layout_
            android:layout_/>

然后你可以在Activity中的onCreate()中做->

   val spinner = findViewById<Spinner>(R.id.spinner)
    val items = arrayOf("500g", "1kg", "2kg")
    val adapter = ArrayAdapter<String>(
        this,
        android.R.layout.simple_spinner_dropdown_item,
        items
    )
    spinner.setAdapter(adapter)

您可以从下拉列表中获取监听器:

 spinner.onItemSelectedListener = object : OnItemSelectedListener 
        override fun onItemSelected(
            arg0: AdapterView<*>?,
            arg1: View?,
            arg2: Int,
            arg3: Long
        ) 
            // Do what you want
            val items = spinner.selectedItem.toString()
            
        

        override fun onNothingSelected(arg0: AdapterView<*>?) 
    

【讨论】:

R.layout.simple_spinner_dropdown_item 在哪里发挥作用?它是否包装了 &lt;Spinner ?更新 - 我看到它是一个提供的 Android 布局。不错。【参考方案10】:

您可以通过这些简单的步骤创建微调器

首先在 xml 中创建微调器

<Spinner
        android:id="@+id/select"
        android:layout_
        android:layout_
        android:textColor="#070707"></Spinner>

现在在值中创建字符串数组

 <string-array name="itemselect">
    <item>Repurchase</item>
    <item>Coupons</item>
</string-array>

现在在 java 文件中初始化

public class MemberCart_Activity extends AppCompatActivity 

Spinner select;
@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_member_cart);

 
    select=findViewById(R.id.select);
 ArrayAdapter<String> myadapter=new ArrayAdapter<String>(Main_Activity.this,android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.itemselect));
    myadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    select.setAdapter(myadapter);

【讨论】:

以上是关于如何创建下拉列表?的主要内容,如果未能解决你的问题,请参考以下文章

如何创建下拉列表?

如何使用默认值创建一个空的下拉列表?

如何从 Provider 创建一个下拉列表? (扑)

如何使用 Flask 和 HTML 从 python 列表创建下拉菜单

QT如何实现自定义下拉列表

如何创建selectMenu小部件创建的下拉列表的固定标头?