列表视图搜索未返回正确的相应活动(TextWatcher)

时间:2012-08-01 01:36:26

标签: android listview search filter textwatcher

我有一个列表视图,其中包含相应的活动,这些活动在我点击每个项目时开始。它工作正常。但是当我搜索“Pedro”并点击它时,不要开始正确的活动。它打开了第一个活动“Joao.class”

这是我的代码。拜托,我需要一个详细的解释。我不太熟悉Java,所以有人可以向我解释或告诉我应该在哪里更改代码?

非常感谢!!!

public class Main extends Activity {

   private ListView lv1;
private EditText ed;
private String lv_arr[]=  {"Android","Cupcake","Donut","Eclairs","AndroidPeople","Froyo",};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.ListView01);
ed=(EditText)findViewById(R.id.EditText01);
lv1.setOnItemClickListener(new OnItemClickListener(){

public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {



       if ("João".equals(lv_arr[position])) {
           Intent myIntent = new Intent(Main.this, Joao.class);
           startActivity(myIntent);
       }

       if ("Maria".equals(lv_arr[position])) {
           Intent myIntent = new Intent(Main.this, Maria.class);
           startActivity(myIntent);
       }

       if ("Pedro".equals(lv_arr[position])) {
           Intent myIntent = new Intent(Main.this, Pedro.class);
           startActivity(myIntent);
       }


}

        });





// By using setAdpater method in listview we an add string array in list.
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 ,    lv_arr));
ed.addTextChangedListener(new TextWatcher() {

public void afterTextChanged(Editable s) {
}

public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}

public void onTextChanged(CharSequence s, int start, int before,
int count) {

textlength=ed.getText().length();
arr_sort.clear();
for(int i=0;i<lv_arr.length;i++)
{
if(textlength<=lv_arr[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) lv_arr[i].subSequence(0,    textlength)))
{
arr_sort.add(lv_arr[i]);
}
}
}

lv1.setAdapter(new ArrayAdapter<String>(Main.this,android.R.layout.simple_list_item_1  , arr_sort));

}
});
}

} 

1 个答案:

答案 0 :(得分:0)

我的猜测是,android.R.layout.simple_list_item_1中的数据与数据排序后的数据不匹配。您需要从arr_sort中获取值,而不是查看数组。即:

if ("Pedro".equals(arr_sort.get(position))) {