无法连续多次选择微调器下拉菜单项

时间:2017-06-16 22:04:28

标签: android

我的问题是我可以在微调器下拉菜单中选择一个列表项,但是我不能连续多次选择一个项目而不先选择另一个项目。必须有一种方法来更改父类中的选择参数。知道怎么样?

我的微调器下拉菜单中有几个项目。

dropdownMenu = (Spinner) findViewById(R.id.dropdownMenu);

List<String> list = new ArrayList<>();

list.add("Filters");
list.add("list 2");
list.add("list 3");

ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(this,
        android.R.layout.simple_spinner_item, list);

dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

dropdownMenu.setAdapter(dataAdapter);

我的主要活动扩展了AdapterView.OnItemSelectedListener接口,我使用MainActivity

的实例设置了监听器
dropdownMenu.setOnItemSelectedListener(this);

以下是我在MainActivity

中声明的界面覆盖
public void onItemSelected(AdapterView<?> parent, View view,
                           int pos, long id) {
    // An item was selected. You can retrieve the selected item using
    // parent.getItemAtPosition(pos)
    Log.v(TAG,"SELECTED");

    // There must be a way to change the selected 
    // property to false here
}

public void onNothingSelected(AdapterView<?> parent) {
    // Another interface callback
}

2 个答案:

答案 0 :(得分:0)

您需要实现自定义微调器,如下所示:

SelectedItem

答案 1 :(得分:0)

全部贴出一半答案,所以贴出完整的实现,以方便初学者和更好地理解。

创建一个自定义 Spinner 类,如下所示。

import android.content.Context;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatSpinner;

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

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

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

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

@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
        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
        getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
    }
}
}

现在在 xml 文件中,创建一个微调器。将微调标签 替换为 <yourdomain.yourprojectname.yourpackagename.spinnerclassname>,例如 <com.company.appname.utility.NDSpinner>

在你的java文件中,定义spinner变量如下: 例如:-

NDSpinner ndSpinner = findViewById(R.id.spinnerId);

如需进一步帮助,请发表评论并获得答案。尽快