2011-07-12 40 views
10

嘿大家我已經找了幾個小時試圖找到一個解決方案,我的目標是有一個ListView,當它打開並打開另一個活動。實際上,我知道它能夠在點擊時打開另一個活動,但我如何獲得它以便每個列表項目都能打開它自己的活動?我很抱歉,如果這個問題已經回答了,但我發現這個鏈接並不能真正說明什麼代碼做[是的,我是新手:)]Listview,打開新的活動onClick

這是使用

@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     String[] countries = getResources().getStringArray(R.array.countries_array); 
     setListAdapter(new ArrayAdapter<String>(this, R.layout.newfile, countries)); 

     ListView lv = getListView(); 
     lv.setTextFilterEnabled(true); 

     lv.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, View view, 
      int position, long id) { 
      // When clicked, show a toast with the TextView text 
      Intent myIntent = new Intent(view.getContext(), Html_file.class); 
      startActivityForResult(myIntent, 0); 

     } 
     }); 
    } 
} 

回答

17
代碼IM
lv.setOnItemClickListener(new OnItemClickListener() { 
    public void onItemClick(AdapterView<?> parent, View view, 
     int position, long id) { 
     // When clicked, show a toast with the TextView text 
     if(position == 1) { 
      //code specific to first list item  
      Intent myIntent = new Intent(view.getContext(), Html_file1.class); 
      startActivityForResult(myIntent, 0); 
     } 

     if(position == 2) { 
      //code specific to 2nd list item  
      Intent myIntent = new Intent(view.getContext(), Html_file2.class); 
      startActivityForResult(myIntent, 0); 
     } 
    } 
}); 
3

如果你有列表,你可以在位置

lv.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, View view, 
      int position, long id) { 
      // When clicked, show a toast with the TextView text 
      Intent myIntent = new Intent(view.getContext(), Html_file.class); 
      startActivityForResult(myIntent, 0); 

     } 
}); 
1

如果你知道哪些活動是被點擊不同的列表項時要打開在這裏使用開關罩的一些數量有限,那麼就分配ID或TA g到列表項目。
在onItemClick的回調中,您有一個參數View,
用它來獲取id或tag來區分它們並調用相應的Activity。

+0

感謝您爲更復雜的問題提供答案。 – Suhaib

4
public void onItemClick(AdapterView<?> parent, View view, 
    int position, long id) { 
    switch(position) { 
    case 0: Intent newActivity = new Intent(this, i1.class);  
       startActivity(newActivity); 
       break; 
    case 1: Intent newActivity = new Intent(this, i2.class);  
       startActivity(newActivity); 
       break; 
    case 2: Intent newActivity = new Intent(this, i3.class);  
       startActivity(newActivity); 
       break; 
    case 3: Intent newActivity = new Intent(this, i4.class);  
       startActivity(newActivity); 
       break; 
    case 4: Intent newActivity = new Intent(this, i5.class);  
       startActivity(newActivity); 
       break; 
    } 
}