2014-02-19 158 views
0

我有一個充滿字符串 的ArrayList一個ListView,我想使它點擊..但我不能識別哪些項目被點擊該項目被點擊的可點擊列表視圖

我做了這但它不起作用!

有沒有辦法知道被點擊的字符串? 如果不是 有沒有辦法知道點擊項目的位置?

public class SearchResults extends Activity{ 

    public ArrayList<String> findMovieByName(String name) { 
     ArrayList<movie> matches = new ArrayList<movie>(); 
     // go through list of members and compare name with given name 
     for(movie movie : MovieReg_activity.movies) { 
      if (movie.getName().contains(name)) { 
       matches.add(movie); // adds matching member to the return list 

      } 
     } 
     ArrayList<String> matchesNames = new ArrayList<String>(); 
      int x=0; 
      for(movie movie : matches) { 
      String name65 = movie.getName(); 
      matchesNames.add(x,name65); 
      x++ ; 
       } 

     return matchesNames; // return the matches, which is empty when no member with the given name was found 
    } 
      @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.test); 
     ListView lv=(ListView)findViewById(R.id.listView1); 
     TextView tv=(TextView)findViewById(R.id.textView1); 


     Bundle bundle =getIntent().getExtras(); 
     if(bundle!=null){ 
     String searchbar =bundle.getString("search value"); 


     ArrayList<String> list = findMovieByName(searchbar); 
      int match_size=list.size(); 
      tv.setText("no of matches=" +match_size); 



     ArrayAdapter<String> ad = new ArrayAdapter<String>(SearchResults.this, android.R.layout.simple_list_item_1, list); 
     lv.setAdapter(ad); 

     lv.setOnItemClickListener(new OnItemClickListener() { 

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

        if(position.equals(1)){   
         Toast.makeText(SearchResults.this,"1 chosen", Toast.LENGTH_LONG).show(); 
        } else { 
         Toast.makeText(SearchResults.this,"nothing", Toast.LENGTH_LONG).show(); 

        }   

      } 
     }); 

     } 
    } 
    } 

回答

0
final ListView lv = (ListView) findViewById(R.id.yourListView); 

lv.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) { 
     String selectedFromList =(String) (lv.getItemAtPosition(myItemInt)); 

     }     
});