2010-12-13 42 views
6

Tôi có biểu mẫu Android cần cập nhật chính nó dựa trên các lựa chọn nhất định. Biểu mẫu hiện được tạo thành từ 2 Spinners (A và B). Spinner B không được tạo cho đến khi lựa chọn của Spinner A được thực hiện. Sau khi lựa chọn được thực hiện B sẽ được hiển thị để xem và nội dung của nó được điền động dựa trên lựa chọn của A. Đây là mã của tôi:Android Spinner - Cách chọn danh sách mặc định là none

public class MyForm extends Activity 
{ 
    private final int SEL_ACTIVATE = 0; 
    private final int SEL_DEACTIVATE = 1; 

    private static final String[] actionList = {"Activate", "Deactivate" }; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     table = (TableLayout) findViewById(R.id.table); 

     showListA(table); 
    } 

    public void showListA(View v) 
    {   
     rowAction = new TableRow(this); 

     Spinner spinner = new Spinner(this); 
     spinner.setPrompt("Select..."); 
     spinner.setOnItemSelectedListener(
      new OnItemSelectedListener() 
      { 
       public void onItemSelected(AdapterView<?> parent, View v, int position, long id) 
       { 
        switch (position) 
        { 
        case SEL_ACTIVATE: 
        case SEL_DEACTIVATE: 
         showListB(v); 
         break; 
        } 
       } 

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

     ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, actionList); 
     adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); 
     spinner.setAdapter(adapter); 

     rowAction.addView(tvAction); 
     rowAction.addView(spinner); 

     table.addView(rowAction, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
    } 

    ... 
} 

Mã này hoạt động chính xác. Khi chọn "Kích hoạt" hoặc "Hủy kích hoạt" từ danh sách, showListB() thực hiện rất giống với showListA() trong cách tạo hàng mới chứa Nhãn và Spinner.

Vấn đề là, theo mặc định, "Kích hoạt" được hiển thị trong Spinner thực hiện showListB() và phải tắt bat, phần thứ hai của biểu mẫu được tạo dựa trên tùy chọn "Kích hoạt". Cách giải quyết duy nhất mà tôi có thể đưa ra là thêm trường thứ ba vào Spinner như vậy:

private static final String[] actionList = {"None", "Activate", "Deactivate" }; 

... 

switch (position) 
{ 
case SEL_NONE: 
    break; 
case SEL_ACTIVATE: 
case SEL_DEACTIVATE: 
    showListB(v); 
    break; 
} 

Tác phẩm này ... nhưng tôi không muốn có tùy chọn thứ ba trong danh sách. Tôi chỉ muốn nó, theo mặc định, được để trống hoặc hiển thị một số loại văn bản 'nhắc' mà không phải là một tùy chọn trong danh sách khi nó được nhấn. Điều này có thể không?

Cảm ơn

EDIT:

nội dung xml:

<Spinner 
    android:id="@+id/spinnerAction" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/> 

Trả lời

4

My dữ liệu sizes.xml:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <string-array name="chunks"> 
     <item>2</item> 
     <item>4</item> 
     <item>8</item> 
     <item>16</item> 
     <item>32</item> 
    </string-array> 
</resources> 

Trong main.xml:

<Spinner android:id="@+id/spinnerSize" 
android:layout_marginLeft="50px" 
android:layout_width="fill_parent"     
android:drawSelectorOnTop="true" 
android:layout_marginTop="5dip" 
android:prompt="@string/SelectSize" 
android:layout_marginRight="30px" 
android:layout_height="35px" /> 

Trong Mã Java:

Spinner spinnerSize; 
ArrayAdapter adapter; 

... 

spinnerSize = (Spinner)findViewById(R.id.spinnerSize); 
adapter = ArrayAdapter.createFromResource(this, R.array.chunks, android.R.layout.simple_spinner_item); 
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
spinnerSize.setAdapter(adapter); 
spinnerSize.setOnItemSelectedListener(new MyOnItemSelectedListener()); 

... 

class MyOnItemSelectedListener implements OnItemSelectedListener { 

    public void onItemSelected(AdapterView<?> parent, 
     View view, int pos, long id) { 
     chunkSize = new Integer(parent.getItemAtPosition(pos).toString()).intValue(); 
    } 
    public void onNothingSelected(AdapterView<?> parent) { 
     // Dummy 
    } 
} 

Vì vậy, mặc dù tôi có thể thấy 2 là mục mặc định đầu tiên của mình, không có gì xảy ra trừ khi người dùng thực sự chọn nó.

Hy vọng điều này sẽ hữu ích!

+0

Hãy đưa ra lý do khi bạn nghĩ rằng câu trả lời không hữu ích (-1), theo cách đó tất cả có thể hiểu tại sao câu trả lời này không tốt và cho thấy cách tốt hơn để làm điều đó! Cảm ơn. – TheCottonSilk

+0

Để làm rõ, điều này có tác dụng vì bạn đang thiết lập 'OnItemSelectedListener' ** sau ** bạn đã đặt' Adapter' đúng chưa? –

+0

Biến chunkSize là gì? – CACuzcatlan

-1

Hãy thử thiết lập này trong xml với thuộc tính nhanh chóng:

android:prompt="@string/prompt" 

này cũng sẽ điền vào đầu hộp thoại spinner.

Tôi đã bỏ qua điều này trong tài liệu. Lời nhắc không thể được áp dụng trực tiếp. Thuộc tính nhắc phải được tham chiếu từ một nguồn khác. Thử tham khảo giá trị chuỗi.

Tài liệu từ Android:

android:prompt 

Since: API Level 
The prompt to display when the spinner's dialog is shown. 
Must be a reference to another resource, in the form "@[+][package:]type:name" or to a  theme attribute in the form "?[package:][type:]name". 
This corresponds to the global attribute resource symbol prompt. 
+0

tôi tin rằng tôi đang làm điều này trong nguồn Java qua 'spinner.setPrompt ("Hành động có sẵn");'. Nhưng tôi vừa cố gắng thêm dòng nguồn của bạn vào XML và nhận được lỗi sau: 'error: Error: Các kiểu chuỗi không được cho phép (tại 'prompt' với giá trị 'test').' Đó là lẻ, vì API cho ' 'lời nhắc nói phải là đối số hợp lệ ... – linsek

+0

Tôi đã bỏ qua tham chiếu trong tài liệu. Nhắc phải được tham chiếu. – Phobos

+0

Tôi rất tiếc, tôi không thực hiện theo chỉnh sửa của bạn. "Thử tham khảo giá trị chuỗi"? – linsek

1

Spinner sẽ luôn có lựa chọn. Những gì bạn có thể làm là làm cho Spinner hiển thị nội dung như "Chọn" hoặc "Chọn tùy chọn" ...

Để làm điều này bạn có thể làm tùy chọn danh sách của bạn là

actionList = {"Select", "Desactivate" } 

public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {    
     actionList[0] = "Activate"; 
     ... 
} 

hoặc bạn có thể làm điều gì đó phức tạp hơn như ghi đè các Spinner Xem hoặc đặt một nút thay vì không có gì trên đó và khi nó được nhấp bạn tạo spinner của bạn.

2

Nếu bạn muốn, có một decorater spinnerAdapter phù thủy tự động thêm một giá trị mặc định:

 


    protected class SpinnerAdapterWithNoValue implements SpinnerAdapter { 

     private SpinnerAdapter _current; 
     private final static String defaultValue = "Choisir"; 

     public SpinnerAdapterWithNoValue(SpinnerAdapter base) { 
      _current = base; 
     } 

     @Override 
     public int getCount() { 
      return _current.getCount() + 1; 
     } 

     @Override 
     public Object getItem(int position) { 
      if (position == 0 || position == -1) { 
       return null; 
      } 
      return _current.getItem(position - 1); 
     } 

     @Override 
     public long getItemId(int position) { 
      if (position == 0 || position == -1) { 
       return -1; 
      } 
      return _current.getItemId(position - 1); 
     } 

     @Override 
     public int getItemViewType(int position) { 
      if (position == 0 || position == -1) { 
       return -1; 
      } 
      return _current.getItemViewType(position - 1); 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      if (position == 0 || position == -1) { 
       final TextView v = (TextView) ((LayoutInflater) getContext().getSystemService(
         Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.spinner_text, parent, false); 
       v.setText(defaultValue); 
       return v; 
      } 
      return _current.getView(position - 1, convertView, parent); 
     } 

     @Override 
     public int getViewTypeCount() { 
      return _current.getViewTypeCount(); 
     } 

     @Override 
     public boolean hasStableIds() { 
      return _current.hasStableIds(); 
     } 

     @Override 
     public boolean isEmpty() { 
      return _current.isEmpty(); 
     } 

     @Override 
     public void registerDataSetObserver(DataSetObserver observer) { 
      _current.registerDataSetObserver(observer); 
     } 

     @Override 
     public void unregisterDataSetObserver(DataSetObserver observer) { 
      // TODO Auto-generated method stub 
      _current.unregisterDataSetObserver(observer); 
     } 

     @Override 
     public View getDropDownView(int position, View convertView, ViewGroup parent) { 
      // TODO Auto-generated method stub 
      if (position == 0 || position == -1) { 
       CheckedTextView v = (CheckedTextView) ((LayoutInflater) getContext().getSystemService(
         Context.LAYOUT_INFLATER_SERVICE)).inflate(android.R.layout.simple_spinner_dropdown_item, parent, 
         false); 
       v.setText(defaultValue); 
       return v; 
      } 
      return _current.getDropDownView(position - 1, convertView, parent); 
     } 
    } 

 

Sau đó, bạn có thể tạo spinner của riêng bạn sử dụng decorater này:

 


    public class SpinnerWithNoValue extends Spinner { 

     public SpinnerWithNoValue(Context context) { 
      super(context); 
     } 

     public SpinnerWithNoValue(Context context, AttributeSet attrs) { 
      super(context, attrs); 
     } 

     public SpinnerWithNoValue(Context context, AttributeSet attrs, int defStyle) { 
      super(context, attrs, defStyle); 
     } 

     @Override 
     public void setAdapter(SpinnerAdapter orig) { 
      final SpinnerAdapter adapter = new SpinnerAdapterWithNoValue(orig); 
      super.setAdapter(adapter); 

      try { 
       final Method m = AdapterView.class.getDeclaredMethod("setNextSelectedPositionInt", int.class); 
       m.setAccessible(true); 
       m.invoke(this, -1); 

       final Method n = AdapterView.class.getDeclaredMethod("setSelectedPositionInt", int.class); 
       n.setAccessible(true); 
       n.invoke(this, -1); 

      } catch (Exception e) { 
       throw new RuntimeException(e); 
      } 
     } 

     /* 
     * getSelectedItem renvoi null si la valeur par defaut est séléctionnée 
     * 
     * @see android.widget.AdapterView#getSelectedItem() 
     */ 
     @Override 
     public Object getSelectedItem() { 
      return super.getSelectedItem(); 
     } 
    } 

 

Bạn chỉ cần phải thay đổi khai báo spinner trong bố cục xml của bạn:

 


com.myproject.SpinnerWithNoValue 

 

Nếu bạn muốn, bạn có thể thay đổi mã để đặt văn bản mặc định trong thẻ của spinner của bạn.

-1

Tôi chỉ là một kẻ ăn xin phát triển ứng dụng Android và đang đối mặt với một vấn đề tương tự; đã có thể sắp xếp nó ra sử dụng một solution- đơn giản này làm việc cho tôi, hy vọng nó làm cho bạn thêm:

public class AdmissionActivity mở rộng Hoạt động thực hiện OnItemSelectedListener {

int i; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    i=0; 
      ......... 

      } 

........ .....

public void onItemSelected(AdapterView<?> parent, View view, 
     int pos, long id){ 

    if(i!=0){ 
     //do wat you want; 
    } 
    else i=1; 
      } 
      //initially the activity will be loaded and nothing will happen (since 
       // i=0); and then appropriate action will be taken since i would hav been 

// thay đổi để sumtng khác

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