简体   繁体   中英

[Android]How to get item number(position) from a String[]

I have a String[] that contains number of strings, what I'm trying to do is set a ProgressBar's progress according to which string is used.

For example, I have already determined number of strings and set max progress of progress bar accordingly; here is the list:

 "zero one two three four five six seven eight nine...."

..

 String[] cpu0freqslist = cpu0freqs.split("\\s");
 countcpu0 = cpu0freqslist.length;

..

 ProgressBar cpu0progbar = (ProgressBar)findViewById(R.id.progressBar1);
 cpu0progbar.setMax(countcpu0);

But now I need to set the progress of progressbar according to the item that is used, and I don't know how to get item position.

So if I want to set a progress bar to the position of item five (in this case it would be 6) how can I do that - how can I get the position of item five?

essentially what you're looking for is a indexOf(...) ...

since arrays don't have it, you'll have to search thru it to find the desired string. so something like this (feel free to optimize)

 public int indexOfString(String searchString, String[] domain)
 {
     for(int i = 0; i < domain.length; i++)
        if(searchString.equals(domain[i]))
           return i;

     return -1;
 }

Then again, if you dynamically fetch your String[] data, it would be wiser to use an ArrayList and just invoke list.indexOf(myString);

You can use the Arrays utility class:

List<String> list = Arrays.asList(new String[] {"First", "Second", "Third"});
int index = list.indexOf("Second"); // 1

cpu0freqslist[5]

这对你有帮助吗?

Ok let me break your query into parts...

String[] arr = {"First","Second","Third"};   // String array with 3 elements

for(int i=0 ; i<arr.length ; i++){

    int j = i ;                          // Position of the element

    String s = a[i] ;                    // Element Itself

   System.out.println("The "+i+" element is  "+s);


  }

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