Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

android - How to set position in spinner?

I read with BufferedReader text from a system file; this text contains, for example, 5 WORDS, but in another case it can contain fewer or more words. Then I put this text (the mentioned words) into a SINGLE string and saved that string to shared preferences. Then I made a spinner from this string. Code is as follows:

Spinner spinner = new Spinner(this);
    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, yourString.split(" "));
    spinner.setAdapter(spinnerArrayAdapter);

Then I read text from another file. This text always contains one word. And this word is the same as one of the words which I had read from the first file (for example, if the first file which I read contained 5 words and one of these words was "black", the second file which I read also contains "black"). And I need to make this particular word (which exists in both files) as the default chosen option in my spinner.

For example:

First string contains: red, blue, yellow, black, white

Second string contains: yellow

I make a spinner from first string so options in spinner are populated exactly like this: "red, blue, yellow, black, white" and the default selected option is red (because it happens to be the first one in my first string), but I need to make yellow as the default selected option in this case, because second string contains "yellow". The words in both string are always different.

BTW: I know how to save the position in a spinner, but I don't know how to set the position in a spinner if I compare two strings and one of them contains more words.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is solution, thanks to sfratini for help.

Use:

spinner.setSelection(getIndex(spinner, myString));

Then:

private int getIndex(Spinner spinner, String myString){

        int index = 0;

        for (int i=0;i<spinner.getCount();i++){
            if (spinner.getItemAtPosition(i).equals(myString)){
                index = i;
            }
        }
        return index;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...