如何在ListView(Android)中选择ListItem?

时间:2012-01-19 11:23:06

标签: android

我是android的新手。

我使用Listview在搜索栏中工作,它工作正常,但我想从ListView中选择ListItem。请任何人帮助我。

感谢。

我尝试了源代码:      private ListView lv1;      私人EditText ed;      SitesList sitesList = null;

        private String lv_arr[] = {"sam","priya","rahul",};

        private ArrayList<String> arr_sort= new ArrayList<String>();
        int textlength=0;

        @Override
        public void onCreate(Bundle savedInstanceState)
        {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.searchbar);

    //   index = lv1.getSelectedItemPosition();
    //     selObj = lv1.getSelectedItem();
    //   System.out.println("selObj "+ selObj );

        lv1=(ListView)findViewById(R.id.ListView01);
        ed=(EditText)findViewById(R.id.EditText01);

         sitesList = MyXMLHandler.sitesList;
         String LoginToken = sitesList. getCourtName().toString();
         System.out.println("ResultLoginToken" + LoginToken);

        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>(Searchbar.this,android.R.layout.simple_list_item_1, arr_sort));
        }
        });
        }
        }

1 个答案:

答案 0 :(得分:1)

在listView(lv)上放置onClick监听器,如下所示。

lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
System.out.println("items--"+lstBarsName.getItemIdAtPosition(arg2));

            }
        });