如何在微调器中设置位置? [英] How to set position in spinner?

查看:31
本文介绍了如何在微调器中设置位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 BufferedReader 从系统文件中读取文本;例如,此文本包含 5 个单词,但在另一种情况下,它可以包含更少或更多的单词.然后我将此文本(提到的单词)放入一个 SINGLE 字符串并将该字符串保存到共享首选项中.然后我用这个字符串做了一个微调器.代码如下:

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);

然后我从另一个文件中读取文本.此文本始终包含一个单词.这个词和我从第一个文件中读到的一个词相同(例如,如果我读的第一个文件包含 5 个词,其中一个词是黑色",那么我读的第二个文件也是包含黑色").我需要将这个特定的词(两个文件中都存在)作为我微调器中的默认选择选项.

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.

例如:

第一个字符串包含:红、蓝、黄、黑、白

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

第二个字符串包含:黄色

Second string contains: yellow

我从第一个字符串制作了一个微调器,因此微调器中的选项完全像这样填充:红色,蓝色,黄色,黑色,白色",默认选择的选项是红色(因为它恰好是我第一个string),但在这种情况下我需要将黄色作为默认选择选项,因为第二个字符串包含黄色".两个字符串中的单词总是不同的.

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.

推荐答案

这是解决方案,感谢 sfratini 的帮助.

Here is solution, thanks to sfratini for help.

用途:

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

然后:

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;
}

这篇关于如何在微调器中设置位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆