对于我们的项目,我需要实现以下内容:当在另一个微调器中选择了相同的项时,将禁用一个微调器项(反之亦然)。关于如何实现它的任何想法,或者是否已经存在这样的实现(可能在适配器或Spinner类中)?
我知道两个微调器都具有相同的项目列表,因此您可以设置第一个微调器并获取位置,并在第二个微调器中自动禁用该位置。
public class MainActivity extends AppCompatActivity {
int selectedItemSpinner1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Items in the two Spinners
String[] languages = new String[]{
"English",
"French",
"German",
"Spanish",
"Italien"
};
List<String> languagesList = new ArrayList<>(Arrays.asList(languages));
// Set the spinner 1 and get the selected value position
Spinner spinner1 = findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,R.layout.support_simple_spinner_dropdown_item,languagesList);
spinner1.setAdapter(adapter);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedItemSpinner1 = position;
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Set the spinner 2 and disable the position
Spinner spinner2 = findViewById(R.id.spinner2);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,R.layout.spinner_item,languagesList){
@Override
public boolean isEnabled(int position){
if(position == selectedItemSpinner1)
{ return false;
}
else
{
return true;
}
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if(position==selectedItemSpinner1) {
// Set the disable item text color
tv.setTextColor(Color.GRAY);
}
else {
tv.setTextColor(Color.BLACK);
}
return view;
}
};
spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
spinner2.setAdapter(spinnerArrayAdapter);
}