2012-04-23 39 views
0

我想搜索字符串数组并将结果获取到ListView中。Android通过字符串数组搜索并将结果导入ListView

所以,如果我有

<string-array name="Colors"> 
    <item>Red</item> 
    <item>Yellow</item> 
    <item>Blue</item> 
    <item>DarkRed</item> 
</string> 

,我搜索“红”,我应该进入ListView的两个项目。对于每个项目,我想知道ID到字符串数组和字符串值,这将显示在ListView中。

在搜索结果时,我想显示一个ProgressBar(不确定状态),当所有完成时消失。

第一步是将字符串数组获取到List或String []中,然后创建一个新的Thread来比较数组中的每个项目,并将ListView与搜索文本匹配。

我不知道哪个是最好的做法。我的代码是这样的:

public class SearchActivity extends Activity { 
    private ProgressBar mProgress; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.search); 

     mProgress = (ProgressBar) findViewById(R.id.Progress); 

     new Thread(new Runnable() { 
      public void run() { 
      int item_pos = 0; 
      int item_count = 0; 

      String[] Colors = getResources().getStringArray(R.array.Colors); 
       item_count = Colors.length(); 

       mProgress.setVisibility(View.VISIBLE); 

       while (item_pos < item_count) { 
        // Compare with the search text 
        // Add it to the ListView (I don't know how) 
        item_pos +=1; 
       } 
       mProgress.setVisibility(View.GONE); 
      } 
     }).start(); 
    } 
} 

所以,我的问题:

  1. 我如何获得这两个项目的id和字符串,则比较搜索文本的每个文本值?
  2. 如何添加一个项目到ListView?
  3. 为什么ProgressBar不可见?该进度XML代码是这样的:

    <ProgressBar 
        android:id="@+id/Progress" 
        style="@android:style/Widget.ProgressBar.Small" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:indeterminate="true" 
        android:visibility="visible" /> 
    

感谢您的所有建议和帮助!

回答

3

下面是我如何解决这个问题。

首先,我会得到我的string-array这样的:

Resources res = getResources(); 
    String[] colors = res.getStringArray(R.array.Colors); 
    // transform into ArrayList for ease of use 
    ArrayList<String> colorsList = Arrays.asList(colors); 

搜索列表中所需的序列,并删除任何不需要的元素:

for (String s : colorsList) { 
    if (!s.contains("red")) { // hardcoded, only to illustrate my logic 
     colorsList.remove(s); 
    } 
} 

现在,你有免费的清单不需要的元素,只需将它绑定到你的ListView,为此我推荐ArrayAdapter。该文档包含一篇关于basic ListView usage的伟大文章。

如果您的Activity仅包含一个ListView作为唯一元素,那么您可以从ListActivity而不是Activity扩展活动。它会给你一些新的好处,比如简单地调用getListView()以便轻松获得你的ListView。

就您的ProgressBar而言,我建议您查看AsyncTask类,它将提供更优雅的方式来处理应用程序中的线程。 Android Dev Team建议您使用AsyncTask,而不是您现在使用的经典Runnable方法。

最后,如果您一般需要查看更多关于ListView的代码片段,您应该看看here,它充满了来自Android团队的示例。当我开始使用Android时,对我来说非常有帮助,并且无法摆脱ListViews的束缚。

希望得到这个帮助!

+0

感谢您的帮助。我会在一个Async类中做这个,我想我会从中获得双重优势。感谢你的宝贵时间! – ali 2012-04-23 19:36:26