Android Spinner选择了Item操作

时间:2016-09-09 10:06:01

标签: java android android-spinner

我的目标是显示所选微调器项目字符串的一部分,作为所选项目。在Spinner选项中,我希望显示完整的字符串,但只选择它的第一部分。例如:

选择:“赛车”> show:“赛车”,

选择:“快车”>显示:“快”

这可能吗?我的代码:

 private void defineRacingCarsArray(){
        racingCarsArray = Arrays.asList(
                "Racing Car",
                "Fast Car"
        );
    }



private void defineRacingCarsCodeSpinner(){
        racingCarsCodeSpinner = (Spinner) view.findViewById(R.id.cars_code_spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        for (int i = 0; i < racingCarsArray.size(); ++i) {
            adapter.add(racingCarsArray.get(i));
        }
        racingCarsCodeSpinner.setAdapter(adapter);
        racingCarsCodeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                parent.getItemAtPosition(position);
                String car = racingCarsArray.get(position);
             ;
            }

            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

1 个答案:

答案 0 :(得分:1)

试试这个,

racingCarsCodeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // here you have to update 
        TextView selectedView = (TextView) view;
        selectedView.setText(racingCarsArray.get(position).split(" ",2)[0]);
    }
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
});