如何在 Android 中显示组合框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3024656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:20:57  来源:igfitidea点击:

How can I show a combobox in Android?

androidcombobox

提问by James

How can I show a combobox in Android?

如何在 Android 中显示组合框?

回答by gruntled

In android it is called a Spinner you can take a look at the tutorial here.

在 android 中,它被称为 Spinner,您可以在此处查看教程。

Hello, Spinner

你好,纺纱机

And this is a very vague question, you should try to be more descriptive of your problem.

这是一个非常模糊的问题,您应该尝试对您的问题进行更多描述。

回答by Raneez Ahmed

Here is an example of custom combobox in android:

这是android中自定义组合框的示例:

package myWidgets;
import android.content.Context;
import android.database.Cursor;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;

public class ComboBox extends LinearLayout {

   private AutoCompleteTextView _text;
   private ImageButton _button;

   public ComboBox(Context context) {
       super(context);
       this.createChildControls(context);
   }

   public ComboBox(Context context, AttributeSet attrs) {
       super(context, attrs);
       this.createChildControls(context);
}

 private void createChildControls(Context context) {
    this.setOrientation(HORIZONTAL);
    this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                   LayoutParams.WRAP_CONTENT));

   _text = new AutoCompleteTextView(context);
   _text.setSingleLine();
   _text.setInputType(InputType.TYPE_CLASS_TEXT
                   | InputType.TYPE_TEXT_VARIATION_NORMAL
                   | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
                   | InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE
                   | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
   _text.setRawInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
   this.addView(_text, new LayoutParams(LayoutParams.WRAP_CONTENT,
                   LayoutParams.WRAP_CONTENT, 1));

   _button = new ImageButton(context);
   _button.setImageResource(android.R.drawable.arrow_down_float);
   _button.setOnClickListener(new OnClickListener() {
           @Override
           public void onClick(View v) {
                   _text.showDropDown();
           }
   });
   this.addView(_button, new LayoutParams(LayoutParams.WRAP_CONTENT,
                   LayoutParams.WRAP_CONTENT));
 }

/**
    * Sets the source for DDLB suggestions.
    * Cursor MUST be managed by supplier!!
    * @param source Source of suggestions.
    * @param column Which column from source to show.
    */
 public void setSuggestionSource(Cursor source, String column) {
    String[] from = new String[] { column };
    int[] to = new int[] { android.R.id.text1 };
    SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this.getContext(),
                   android.R.layout.simple_dropdown_item_1line, source, from, to);
    // this is to ensure that when suggestion is selected
    // it provides the value to the textbox
    cursorAdapter.setStringConversionColumn(source.getColumnIndex(column));
    _text.setAdapter(cursorAdapter);
 }

/**
    * Gets the text in the combo box.
    *
    * @return Text.
    */
public String getText() {
    return _text.getText().toString();
 }

/**
    * Sets the text in combo box.
    */
public void setText(String text) {
    _text.setText(text);
   }
}

Hope it helps!!

希望能帮助到你!!

回答by vbence

Not tested, but the closer you can get seems to be is with AutoCompleteTextView. You can write an adapter wich ignores the filter functions. Something like:

未经测试,但您似乎可以更接近AutoCompleteTextView。您可以编写一个忽略过滤器功能的适配器。就像是:

class UnconditionalArrayAdapter<T> extends ArrayAdapter<T> {
    final List<T> items;
    public UnconditionalArrayAdapter(Context context, int textViewResourceId, List<T> items) {
        super(context, textViewResourceId, items);
        this.items = items;
    }

    public Filter getFilter() {
        return new NullFilter();
    }

    class NullFilter extends Filter {
        protected Filter.FilterResults performFiltering(CharSequence constraint) {
            final FilterResults results = new FilterResults();
            results.values = items;
            return results;
        }

        protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
            items.clear(); // `items` must be final, thus we need to copy the elements by hand.
            for (Object item : (List) results.values) {
                items.add((String) item);
            }
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}

... then in your onCreate:

...然后在您的 onCreate 中:

String[] COUNTRIES = new String[] {"Belgium", "France", "Italy", "Germany"};
List<String> contriesList = Arrays.asList(COUNTRIES());
ArrayAdapter<String> adapter = new UnconditionalArrayAdapter<String>(this,
    android.R.layout.simple_dropdown_item_1line, contriesList);
AutoCompleteTextView textView = (AutoCompleteTextView)
    findViewById(R.id.countries_list);
textView.setAdapter(adapter);

The code is not tested, there can be some features with the filtering method I did not consider, but there you have it, the basic principles to emulate a ComboBox with an AutoCompleteTextView.

代码未经测试,可能有一些我没有考虑的过滤方法的功能,但是你有它,用 AutoCompleteTextView 模拟 ComboBox 的基本原则。

EditFixed NullFilter implementation. We need access on the items, thus the constructor of the UnconditionalArrayAdapterneeds to take a reference to a List (kind of a buffer). You can also use e.g. adapter = new UnconditionalArrayAdapter<String>(..., new ArrayList<String>);and then use adapter.add("Luxemburg"), so you don't need to manage the buffer list.

编辑固定 NullFilter 实现。我们需要访问项目,因此UnconditionalArrayAdapter需要引用 List(一种缓冲区)的构造函数。您也可以使用 egadapter = new UnconditionalArrayAdapter<String>(..., new ArrayList<String>);然后使用adapter.add("Luxemburg"),这样您就不需要管理缓冲区列表。

回答by Viktor Bre?an

The questions is perfectly valid and clear since Spinner and ComboBox (read it: Spinner where you can provide a custom value as well) are two different things.

这些问题是完全有效和清晰的,因为 Spinner 和 ComboBox(阅读它:Spinner,您也可以在其中提供自定义值)是两个不同的东西。

I was looking for the same thing myself and I wasn't satisfied with the given answers. So I created my own thing. Perhaps some will find the following hints useful. I am not providing the full source code as I am using some legacy calls in my own project. It should be pretty clear anyway.

我自己也在寻找同样的东西,但我对给出的答案并不满意。所以我创造了我自己的东西。也许有些人会发现以下提示很有用。我没有提供完整的源代码,因为我在自己的项目中使用了一些遗留调用。反正应该是很清楚的。

Here is the screenshot of the final thing:

最后的截图如下:

ComboBox on Android

Android 上的组合框

The first thing was to create a view that will look the same as the spinner that hasn't been expanded yet. In the screenshot, on the top of the screen (out of focus) you can see the spinner and the custom view right bellow it. For that purpose I used LinearLayout (actually, I inherited from Linear Layout) with style="?android:attr/spinnerStyle". LinearLayout contains TextView with style="?android:attr/spinnerItemStyle". Complete XML snippet would be:

第一件事是创建一个与尚未展开的微调器看起来相同的视图。在屏幕截图中,在屏幕顶部(失焦),您可以看到微调器和其下方的自定义视图。为此,我将 LinearLayout(实际上,我继承自 LinearLayout)与style="?android:attr/spinnerStyle". LinearLayout 包含带有style="?android:attr/spinnerItemStyle". 完整的 XML 片段将是:

<com.example.comboboxtest.ComboBox 
    style="?android:attr/spinnerStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <TextView
        android:id="@+id/textView"
        style="?android:attr/spinnerItemStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:text="January"
        android:textAlignment="inherit" 
    />

</com.example.comboboxtest.ComboBox>

As, I mentioned earlier ComboBox inherits from LinearLayout. It also implements OnClickListener which creates a dialog with a custom view inflated from the XML file. Here is the inflated view:

正如我之前提到的 ComboBox 继承自 LinearLayout。它还实现了 OnClickListener,它创建一个对话框,其中包含从 XML 文件膨胀的自定义视图。这是膨胀的视图:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" 
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" 
        >
        <EditText
            android:id="@+id/editText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="Enter custom value ..." >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="OK" 
        />
    </LinearLayout>

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
    />

</LinearLayout>

There are two more listeners that you need to implement: onItemClick for the list and onClick for the button. Both of these set the selected value and dismiss the dialog.

您还需要实现另外两个侦听器:用于列表的 onItemClick 和用于按钮的 onClick。这两者都设置了选定的值并关闭对话框。

For the list, you want it to look the same as expanded Spinner, you can do that providing the list adapter with the appropriate (Spinner) style like this:

对于列表,您希望它看起来与展开的 Spinner 相同,您可以这样做,为列表适配器提供适当的 (Spinner) 样式,如下所示:

ArrayAdapter<String> adapter = 
    new ArrayAdapter<String>(
        activity,
        android.R.layout.simple_spinner_dropdown_item, 
        states
    );

More or less, that should be it.

或多或少,应该是这样。

回答by ShAkKiR

Custom made :) you can use dropdown hori/vertical offset properties to position the list currently, also try android:spinnerMode="dialog" it is cooler.

定制 :) 您可以使用下拉水平/垂直偏移属性来定位当前列表,也可以尝试 android:spinnerMode="dialog" 它更酷。

Layout

布局

  <LinearLayout
        android:layout_marginBottom="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <AutoCompleteTextView
            android:layout_weight="1"
            android:id="@+id/edit_ip"
            android:text="default value"
            android:layout_width="0dp"
            android:layout_height= "wrap_content"/>
        <Spinner
            android:layout_marginRight="20dp"
            android:layout_width="30dp"
            android:layout_height="50dp"
            android:id="@+id/spinner_ip"
            android:spinnerMode="dropdown"
            android:entries="@array/myarray"/>
 </LinearLayout>

Java

爪哇

          //set auto complete
        final AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit_ip);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.myarray));
        textView.setAdapter(adapter);
        //set spinner
        final Spinner spinner = (Spinner) findViewById(R.id.spinner_ip);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                textView.setText(spinner.getSelectedItem().toString());
                textView.dismissDropDown();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                textView.setText(spinner.getSelectedItem().toString());
                textView.dismissDropDown();
            }
        });

res/values/string

资源/值/字符串

<string-array name="myarray">
    <item>value1</item>
    <item>value2</item>
</string-array>

Was that useful??

那有用吗??

回答by rve

For a combobox (http://en.wikipedia.org/wiki/Combo_box) which allows free text input and has a dropdown listbox I used a AutoCompleteTextViewas suggested by vbence.

对于允许自由文本输入并具有下拉列表框的组合框(http://en.wikipedia.org/wiki/Combo_box),我使用了AutoCompleteTextViewvbence 的建议。

I used the onClickListenerto display the dropdown list box when the user selects the control.

onClickListener当用户选择控件时,我使用来显示下拉列表框。

I believe this resembles this kind of a combobox best.

我相信这最类似于这种组合框。

private static final String[] STUFF = new String[] { "Thing 1", "Thing 2" };

public void onCreate(Bundle b) {
    final AutoCompleteTextView view = 
        (AutoCompleteTextView) findViewById(R.id.myAutoCompleteTextView);

    view.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
                view.showDropDown();
        }
    });

    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
        this, 
        android.R.layout.simple_dropdown_item_1line,
        STUFF
    );
    view.setAdapter(adapter);
}