2010-06-11 17 views
53

Tôi làm cách nào để hiển thị hộp tổ hợp trong Android?Tôi làm cách nào để hiển thị hộp kết hợp trong Android?

+1

Vui lòng giải thích rõ ràng hơn những gì bạn muốn. Và những gì bạn đã thử. – fretje

+24

@fretje Câu hỏi khá cụ thể. Nếu bạn biết những gì một ** ComboBox ** là, bạn không cần giải thích. Nếu bạn không, bạn vẫn có thể google: http://en.wikipedia.org/wiki/Combo_box – vbence

+1

@vbence: Tôi không nói về ComboBox. Vì Android là một hệ điều hành, bạn cũng có thể hỏi "Cách hiển thị combobox trong Windows", điều này hoàn toàn không cụ thể. – fretje

Trả lời

56

Trong Android, nó được gọi là Spinner bạn có thể xem hướng dẫn tại đây.

Hello, Spinner

Và đây là một câu hỏi rất mơ hồ, bạn nên cố gắng có tính mô tả hơn về vấn đề của bạn.

+15

Tôi đề nghị bạn xem xét điều này trong ngữ cảnh của android phát triển. http://www.designerandroid.com/?p=8. Trong bối cảnh của dev android nó được gọi là một Spinner. Hãy làm nghiên cứu của bạn lần sau. – gruntled

+0

Tôi không nghĩ rằng nguồn đó là độc quyền. Ngược lại, một nguồn sáng tác nhiều hơn một chút cho biết cách khác: http://developer.android.com/guide/topics/ui/custom-components.html – vbence

+3

Có và bằng cách xem trang web bạn đã tự cung cấp, bạn có thể thấy rằng chúng hãy đề cập đến một ComboBox trên trang đó nhưng trong API chỉ có một tham chiếu đến Spinner (http://developer.android.com/resources/tutorials/views/hello-spinner.html) Ở đây, họ nêu rõ rằng một "Spinner là một tiện ích tương tự như một danh sách thả xuống để chọn các mục ". Tôi đồng ý với bạn rằng NÊN này được gọi là một ComboBox như với các triển khai Java khác nhưng trong bối cảnh này nó không phải là. – gruntled

6

Không được thử nghiệm, nhưng bạn càng có thể nhận được gần hơn là với AutoCompleteTextView. Bạn có thể viết một adapter mà bỏ qua các chức năng lọc. Một cái gì đó như:

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

... sau đó trong onCreate của bạn:

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

Mã này được không được kiểm tra, có thể có một số tính năng với phương pháp lọc tôi không xem xét, nhưng có bạn có nó , các nguyên tắc cơ bản để mô phỏng một ComboBox với một AutoCompleteTextView.

Chỉnh sửa Sửa lỗi NullFilter. Chúng ta cần truy cập vào các mục, do đó hàm tạo của UnconditionalArrayAdapter cần tham chiếu đến một Danh sách (loại bộ đệm). Bạn cũng có thể sử dụng ví dụ: adapter = new UnconditionalArrayAdapter<String>(..., new ArrayList<String>); và sau đó sử dụng adapter.add("Luxemburg"), vì vậy bạn không cần quản lý danh sách bộ đệm.

+0

Mã này không đến gần biên dịch. Các cuộc gọi đến getFilter() trông giống như các lần thử tại một vòng lặp vô hạn và publishResults trả về một giá trị từ một phương thức void. Ý tưởng của tổng thể tốt, nhưng ai đó nên sửa lỗi này. – dhakim

10

Dưới đây là một ví dụ về combobox tùy chỉnh trong 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); 
    } 
} 

Hy vọng nó giúp !!

+1

Cảm ơn bạn đã trả lời. Tôi muốn sử dụng tiện ích này nhưng tôi muốn sử dụng một mảng Chuỗi làm nguồn dữ liệu chứ không phải con trỏ. tôi nên làm gì? –

0

Đối với hộp tổ hợp (http://en.wikipedia.org/wiki/Combo_box) cho phép nhập văn bản miễn phí và có hộp danh sách thả xuống, tôi đã sử dụng AutoCompleteTextView theo đề xuất của vbence.

Tôi đã sử dụng onClickListener để hiển thị hộp danh sách thả xuống khi người dùng chọn điều khiển.

Tôi tin rằng điều này giống như loại combobox này tốt nhất.

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

Các câu hỏi hoàn toàn hợp lệ và rõ ràng vì Spinner và ComboBox (đọc: Spinner nơi bạn có thể cung cấp giá trị tùy chỉnh) là hai điều khác nhau.

Tôi cũng đang tìm kiếm chính điều tương tự và tôi không hài lòng với câu trả lời đã cho. Vì vậy, tôi tạo ra điều của riêng tôi. Có lẽ một số sẽ tìm thấy các gợi ý sau hữu ích. Tôi không cung cấp mã nguồn đầy đủ vì tôi đang sử dụng một số cuộc gọi kế thừa trong dự án của riêng mình. Nó phải được khá rõ ràng anyway.

Dưới đây là ảnh chụp màn hình trong những điều cuối cùng:

ComboBox on Android

Việc đầu tiên là tạo ra một cái nhìn đó sẽ trông giống như các spinner chưa được mở rộng được nêu ra. Trong ảnh chụp màn hình, ở phía trên cùng của màn hình (ngoài tiêu điểm), bạn có thể thấy trình quay và chế độ xem tùy chỉnh ngay bên dưới màn hình. Vì mục đích đó, tôi đã sử dụng LinearLayout (thực ra, tôi được kế thừa từ Linear Layout) với style="?android:attr/spinnerStyle".LinearLayout chứa TextView với style="?android:attr/spinnerItemStyle". Đoạn mã XML hoàn chỉnh sẽ là:

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

Như, tôi đã đề cập trước đó ComboBox kế thừa từ LinearLayout. Nó cũng thực hiện OnClickListener, nó tạo ra một hộp thoại với một khung nhìn tùy chỉnh được tăng lên từ tệp XML. Đây là chế độ xem được tăng cao:

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

Có hai trình nghe khác mà bạn cần triển khai: onItemNhấp vào danh sách và nhấp vào nút. Cả hai giá trị này đều đặt giá trị đã chọn và loại bỏ hộp thoại.

Đối với danh sách, bạn muốn nó trông giống như mở rộng Spinner, bạn có thể làm điều đó cung cấp các bộ chuyển đổi danh sách với thích hợp (Spinner) kiểu như thế này:

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

Nhiều hơn hoặc ít hơn, mà nên là nó.

+0

Có vẻ tốt. Tôi đang cố gắng triển khai giải pháp của bạn, nhưng tôi mới phát triển Android và tôi hơi bối rối về vị trí đặt các đoạn mã. Bạn có nhớ sửa đổi một chút để giải thích làm thế nào để thực hiện nó? –

2

Tùy chỉnh thực hiện :) bạn có thể sử dụng các thuộc tính offset hori/dọc thả xuống để định vị danh sách hiện tại, cũng dùng thử 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 ​​/ chuỗi

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

Có hữu ích không ??

Các vấn đề liên quan