简体   繁体   中英

How to get the next/previous item from a spinner on button click?

I trying to implement something that looks like this.

在此处输入图片说明

The spinner contains a list of items that I fill using array adapter.

On button clicks I want to change the spinner's selected item to the next/previous item depending on whichever button is clicked. Is possible to do that? I'm using spinner because I've to fill a ListView above depending on the item selected in the spinner.

Can I use something else other than a spinner and buttons for this purpose?

Regards.

Use:

pirvate Spinner mySpinner;
private int ItemPosition;
private Button ButtonNext;
private Button ButtonPrevious;

in your onResume() :

ItemPosition = mySpinner.getSelectedItemPosition();

and your buttons:

ButtonNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mySpinner.setSelection(mySpinner.getItemAtPosition(ItemPosition++));
    }
});

ButtonPrevious.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mySpinner.setSelection(mySpinner.getItemAtPosition(ItemPosition--));
    }
});

what you can do is get the position of current item showing in spinner

and then in onclick event of back button this check is important cos if spinner showing element at zero and you press back button then poition will be -1; and will give exception.

 forward_Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            int position = mySpn.getSelectedItemPosition();
            if(position>0){
            position=position-1;
            mySpn.setSelection(position);

      }


        }
    });
 }

and in onclick event of forward button

below if check is important cos if your position is greater then size of your arraylist showing in spinner then it will also give exception.

previous_Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

                 int position = mySpn.getSelectedItemPosition();
                 if(position<your_list.size()){
                 position=position+1;
                 mySpn.setSelection(position);

             }

        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM