Reputation: 2613
I have an app with 10 list items.All the items onClick have the same layout between them.I have created a new class for every item and using a switch method to move to every activity.Is there any way to make it more simple( and dont have 10 classes but less)?Thanks
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;
//and i have 8 more cases here
The class mothe.class and the diadromestherisos.class are exactly the same,i m getting the same content view and i m only changing the text and the images(from .setText and.setImageResource).Hope my problem is understandable!
Upvotes: 1
Views: 72
Reputation: 23171
If they're all the same except for the text and image, then you really only need 1 Activity class to handle all 10 cases. What you can do in your switch is populate a Bundle with the ids of the text resource and the drawable resource and pass that into the activity.
So your switch would look like:
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
}
then in your YourNewActivity class, you need to read in the extras and use them to populate your UI:
public void onCreate(Bundle savedInstanceState){
Bundle extras = getIntent().getExtras();
int textResourceId = extras.getInt("TXT_RESOURCE");
int imgResourceId = extras.getInt("IMG_RESOURCE");
}
Upvotes: 3