Listview搜索问题

时间:2013-06-02 06:52:02

标签: android listview search

我有一个工作perfet的listview。今天我使用此代码向listview添加了一个搜索功能

     inputSearch.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // When user changed the Text
            MainActivity.this.adapter.getFilter().filter(cs);   
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub                          
        }
    });

问题:我的列表视图中有114个项目,所选项目取决于位置,当我搜索并按下我发现它将返回位置1的项目时,我想返回该项目的位置在搜索之前..不是新的位置,无论如何都要解决它?!

1 个答案:

答案 0 :(得分:0)

不,它会根据列表视图/适配器的当前长度返回项目的位置。

为什么重要?

如果您想根据点击的项目开始不同的活动,有很多方法可以做到。当位置固定时,使用列表中的位置选择活动,这不是您的情况,因为用户可以过滤项目。

相反,请根据所点击项目的内容启动活动。

比如说,您的列表视图使用以下项填充:

public static final String [] PLANETS = {
        "Mercury",
        "Venus",
        "Earth",
        "Mars",
        "Jupiter",
        "Saturn",
        "Uranus",
        "Neptune",
};

使用以下ArrayAdapter

mAdapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_1, R.id.text1, PLANETS);

然后,您可以根据所选的实际行星编辑OnItemClickListener以启动活动,而不是选择的位置。

private AdapterView.OnItemClickListener mOnPlanetOnItemClickListener = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int iistPosition, long l) {
        //Notice I don't get the value from the String array
        //Rather, I tell the adapter to give me the text from the selected item. 
        String planet = mAdapter.getItem(iistPosition);
        Intent newActivity = new Intent(Example.this, NextActivity.class);
        newActivity.putExtra("planet", planet);
    }
};

如果您使用自定义适配器,则更容易。

编辑不幸的是,由于您的mp3文件的命名方式,您必须依赖列表位置才能获得适当的文件。

在这种情况下,您可以尝试一些解决方法,例如:

  • 如果您的列表视图使用集合ArrayList或仅List填充,您可以首先获取所选项目的文本,然后根据文本获取实际数组位置项目已选中。

像这样:

private AdapterView.OnItemClickListener mOnPlanetOnItemClickListener = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int iistPosition, long l) {
        //get the text of the current item
        String planet = mAdapter.getItem(iistPosition);
        //get the position of this planet in the original unfiltered array
        int actualListPosition = PLANETS_ARRAY.indexOf(planet);
        //handle the click based on the actualListPosition
    }
};

我希望有帮助