如何在 Android 中显示组合框?

如何在 Android 中显示组合框?

208106 次浏览

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

Hello, Spinner

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

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:

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:

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.

Fixed NullFilter implementation. We need access on the items, thus the constructor of the UnconditionalArrayAdapter needs 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.

Here is an example of custom combobox in 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!!

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

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

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

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.

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

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:

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

<?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.

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:

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

More or less, that should be it.

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

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