eclipse 带有空默认选择的微调器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9048094/
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-09-19 17:37:48  来源:igfitidea点击:

Spinner with an empty default selection

androideclipseandroid-spinner

提问by AAP

I have a Spinnerwhich gets populate using a SimpleCursorAdapter. My cursor has some values, but i need the Spinnerto show an empty option by default.

我有一个Spinner使用SimpleCursorAdapter. 我的光标有一些值,但我需要Spinner默认显示一个空选项。

I don't want to use ArrayAdapter<String>, or CursorWrapperin this app, for some reason.

出于某种原因ArrayAdapter<String>,我不想使用或CursorWrapper在这个应用程序中。

There should be a simpler way to show an empty option in the Spinnerby default.

Spinner默认情况下,应该有一种更简单的方法来显示空选项。

回答by Ralph

You can simply hide the unwanted view in the spinner adapter (getDropDownView ) :

您可以简单地在微调适配器 (getDropDownView) 中隐藏不需要的视图:

In my sample code, defaultposition is the position to hide (like a "Select value" position)

在我的示例代码中,defaultposition 是要隐藏的位置(如“选择值”位置)

public class SpinnerOptionAdapter extends ArrayAdapter<optionsInfos> {

 ...

   @Override

  public View getDropDownView(int position, View convertView, ViewGroup parent)
  {   // This view starts when we click the spinner.
    View row = convertView;
    if(row == null)
    {
        LayoutInflater inflater = context.getLayoutInflater();
        row = inflater.inflate(R.layout.product_tab_produit_spinner_layout, parent, false);
    }

    ...

    optionsInfos item = data.get(position);


    if( (item != null) && ( position == defaultposition)) {
        row.setVisibility(View.GONE);
    } else {
        row.setVisibility(View.VISIBLE);
    }

   ....

    return row;
}


 ...
}

回答by laurie_v

A method I sometimes use to add an extra record such as an "empty" option with a SimpleCursorAdapter destined for a Spinner is by using a UNION clause in my cursor query. EMPTY_SPINNER_STRING could be something like: "-- none specified --" or similar. Use an "order by" clause to get your empty record first and therefore the default value in the Spinner. A crude but effective way of getting the required result without changing the underlying table data. In my example I only want certain spinners to have a default empty value (those with a modifier type of "intensity".

我有时用来添加额外记录(例如带有指向 Spinner 的 SimpleCursorAdapter 的“空”选项)的方法是在我的游标查询中使用 UNION 子句。EMPTY_SPINNER_STRING 可能类似于:“-- 未指定--”或类似内容。使用“order by”子句首先获取空记录,从而获取微调器中的默认值。一种在不更改基础表数据的情况下获得所需结果的粗略但有效的方法。在我的示例中,我只希望某些微调器具有默认的空值(那些带有“强度”修饰符类型的微调器。

public Cursor getLOV(String modifier_type)
//get the list of values (LOVS) for a given modifier
{
    if (mDb == null)
    {
        this.open();
    }
    try {
        MYSQL = "SELECT _ID AS '_id', code, name, type as 'DESC', ordering FROM "+codeTab+" WHERE type = '"+modifier_type+"'" +
                " ORDER BY ordering, LOWER(name)";
        if (modifier_type.equals("intensity")) { //then include a default empty record
            MYSQL = "SELECT _ID AS '_id', code, name as 'NAME', type as 'DESC', ordering FROM "+codeTab+" WHERE type = '"+modifier_type+"'" +
                    " UNION SELECT 9999 AS '_id', '' AS 'code', '"+EMPTY_SPINNER_STRING+"' AS 'NAME', 'intensity' AS 'DESC', 1 AS ordering ORDER BY ordering, name";
        }
        Log.d(TAG, "MYSQL = "+MYSQL);
        return mDb.rawQuery(MYSQL, null);
    }
    catch (SQLiteException exception) {
        Log.e("Database LOV query", exception.getLocalizedMessage());
        return null;
    }
}

回答by IronBlossom

Spinner's OnItemSelectedListenerruns on the compile time as well that fetches the first item to view on the Spinnerselected item.

Spinner'sOnItemSelectedListener也在编译时运行,它获取要在Spinner所选项目上查看的第一个项目。

Add a dummy item (String - null " ") on your SimpleCursorAdapterand use spinner.setSelected(int thatSpecificPostionYouJustAdded).

" "在您的上添加一个虚拟项目 (String-null )SimpleCursorAdapter并使用spinner.setSelected(int thatSpecificPostionYouJustAdded).

回答by Shirane85

After setting the adapter. call setSelection (i used with 0) and right after that set the text color to transparent.

设置好适配器后。调用 setSelection (我使用 0),然后立即将文本颜色设置为透明。

    // Preselect the first to make the spinner text transparent
    spinner.setSelection(0, false);
    TextView selectedView = (TextView) spinner.getSelectedView();
    if (selectedView != null) {
        selectedView.setTextColor(getResources().getColor(R.color.transparent));
    }

Then, set your OnItemSelectedListener (if needed).

然后,设置您的 OnItemSelectedListener(如果需要)。

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

This will make the spinner empty at first time seen. But, if the user will select the first item it will do nothing because 0 is pre selected. For fixing this i used this subclass of spinner. taken from @melquiades's answer:

这将使微调器在第一次看到时为空。但是,如果用户选择第一个项目,它什么都不做,因为 0 是预先选择的。为了解决这个问题,我使用了微调器的这个子类。取自@melquiades 的回答


/** 
  * Spinner extension that calls onItemSelected even when the selection is the same as its previous value
  */
public class FVRSpinner extends Spinner {

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

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

    public FVRSpinner(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setSelection(int position, boolean animate) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position, animate);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }

    @Override
    public void setSelection(int position) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }
}

回答by Joshua Pinter

Create a NullSpinnerItemclass and inject it at the start of the list.

创建一个NullSpinnerItem类并将其注入到列表的开头。

// Class to represent the `null` selection in a List of items in a Spinner.
// There is no easy way to tell Spinner to also include a blank or null value. 
// This allows us to inject this as the first item in the List and handle null values easily.
//
public class NullSpinnerItem {

  @Override
  public String toString() {
    return "None";
  }

}

Then when you're populating your spinner, just get your items and then add it to the first position:

然后,当您填充微调器时,只需获取您的项目,然后将其添加到第一个位置:

items.add( 0, new NullSpinnerItem() ); // items are your items.

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource( R.layout.spinner_list_item);

Spinner spinner = (Spinner) findViewById(spinnerId);
spinner.setAdapter(adapter);

The toString()method is what is displayed in the Spinner.

toString()方法是显示在微调器中的内容。