2011-12-01 61 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"); 

}