2011-12-01 67 views
1

我有一個包含10個列表項目的應用程序。所有onClick項目之間都有相同的佈局。我爲每個項目創建了一個新類,並使用切換方法移動到每個活動。任何方式,使其更簡單的(不要有10個班,但少)?謝謝讓我的代碼更簡單

mylist.add(map); 

      map = new HashMap<String, Object>(); 
      map.put("name", "aa"); 
      map.put("address", "aaa"); 
      map.put("address3", R.drawable.im1); 

      mylist.add(map);// i m adding 10 items like this here 


      ListAdapter mSchedule = new SimpleAdapter(this, mylist, R.layout.row, 
         new String[] {"name", "address","address3"}, new int[] {R.id.TextView1, R.id.TextView2,R.id.imgdiadromes}); 
      listcafe.setAdapter(mSchedule); 



      listcafe.setOnItemClickListener(new OnItemClickListener() { 
      public void onItemClick(AdapterView<?> parent, View view, 
         int position, long id) { 
        switch(position) 
        { 
         case 0:  
         Intent newActivity = new Intent(diadromes.this, monte.class); 
         startActivity(newActivity); 
         break; 
        case 1:  
         Intent newActivity1 = new Intent(diadromes.this, diadromestherisos.class); 
         startActivity(newActivity1); 
         break; 

//我在這裏

類mothe.class和diadromestherisos.class正好8個例同樣,即時獲取相同的內容視圖,即時通訊只改變文本和圖像(從.setText和.setImageResource)。希望我的問題是可以理解的!

回答

3

如果它們除了文本和圖像都是一樣的,那麼你真的只需要一個Activity類來處理所有的10種情況。您可以在交換機中執行的操作是使用文本資源的ID和可繪製資源填充Bundle,並將其傳遞到活動中。

所以,你的開關看起來像:

switch(position){ 
    case 0: 
     Intent newActivity = new Intent(diadromes.this, YourNewActivity.class); 
     newActivity.putExtra("TXT_RESOURCE",R.string.your_text_resource_id); 
     newActivity.putExtra("IMG_RESOURCE",R.drawable.your_img_resource_id); 
     startActivity(newActivity); 
     break; 
    case 1: 
     //similar to above, but populate with the different resource ids 
} 

然後在YourNewActivity類,你需要在額外閱讀並利用它們來填充UI:

public void onCreate(Bundle savedInstanceState){ 
    Bundle extras = getIntent().getExtras(); 
    int textResourceId = extras.getInt("TXT_RESOURCE"); 
    int imgResourceId = extras.getInt("IMG_RESOURCE"); 

}