Как использовать itemClickListener в Spinner на Android - PullRequest
0 голосов
/ 20 декабря 2018

В моем приложении у меня есть один Spinner, и я должен показать некоторые данные с сервера в этот Spinner.
Данные моего сервера имеют:

"sections": [{
            "id": 1,
            "name": "Item 1"
        }, {
            "id": 2,
            "name": "Item 2"
        }, {
            "id": 3,
            "name": "Item 3"
        }]

Дляэто spinner я должен установить текст по умолчанию для первого показа и когда пользователи нажимают на spinners элемент показывать эти элементы вместо текста по умолчанию.

Для этого я пишу коды ниже, но я не знаю, как я могу установить clickListener для этих элементов для получения идентификатора каждого элемента!

Myкод адаптера:

public class DashboardSupportSectionAdapter extends ArrayAdapter<Section> {

    Context context;
    List<Section> model;
    String firstElement;
    boolean isFirstTime;

    public DashboardSupportSectionAdapter(Context context, int textViewResourceId, List<Section> model, String defaultText) {
        super(context, textViewResourceId, model);
        this.context = context;
        this.model = model;
        this.isFirstTime = true;
        setDefaultText(defaultText);
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if (isFirstTime) {
            model.get(0).setName(firstElement);
            isFirstTime = false;
        }
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        notifyDataSetChanged();
        return getCustomView(position, convertView, parent);
    }

    public void setDefaultText(String defaultText) {
        this.firstElement = model.get(0).getName();
        model.get(0).setName(defaultText);
    }

    public View getCustomView(final int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.row_dashboard_support_section, parent, false);
        TextView label = row.findViewById(R.id.spinner_text);
        label.setText(model.get(position).getName());

        return row;
    }

}

Код моей активности:

public class DashboardCreateSupportActivity extends BaseActivity {

    @BindView(R.id.dashboardCreateSupport_sectionSpinner)
    Spinner dashboardCreateSupport_sectionSpinner;
    String defaultTextForSpinner = "Select section";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard_create_support);

        ButterKnife.bind(this);

        dashboardCreateSupport_sectionSpinner.setAdapter(new DashboardSupportSectionAdapter(this, R.layout.row_dashboard_support_section,
                Constants.supportListResponse.getRes().getSections(), defaultTextForSpinner));

    }
}

Я хочу, когда нажимает на каждом элементе, показывает идентификаторэлемента в toast сообщении.

Как я могу это сделать?

Ответы [ 3 ]

0 голосов
/ 20 декабря 2018
dashboardCreateSupport_sectionSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 Constants.supportListResponse.getRes().getSections().get(position).getId();
            }
        });
0 голосов
/ 20 декабря 2018
    dashboardCreateSupport_sectionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Section item  = Constants.supportListResponse.getRes().getSections().getItem(position);
            //use item object
        }
        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

Используйте setOnItemSelectedListener.

Я бы даже хотел предложить изменить код, например:

    final DashboardSupportSectionAdapter dashboardSupportSectionAdapter =new DashboardSupportSectionAdapter(this, android.R.layout.simple_list_item_1,
        sections, "default");
    dashboardCreateSupport_sectionSpinner.setAdapter(dashboardSupportSectionAdapter);

и внутри onItemSelected

    Section item  = dashboardSupportSectionAdapter.getItem(position);
0 голосов
/ 20 декабря 2018
dashboardCreateSupport_sectionSpinner.setOnItemClickListener(new AdapterView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                }

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

                }
            });
...