我有一个包含 10 个列表项的应用程序。所有 onClick 项目之间的布局相同。我为每个项目创建了一个新类,并使用 switch 方法移动到每个 Activity 。有什么办法可以做到吗更简单(并且没有 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;
//我这里还有8个案例
类 mothe.class 和 diadromestherisos.class 完全相同,我得到相同的内容 View ,我只更改文本和图像(来自 .setText 和 .setImageResource)。希望我的问题是可以理解的!
最佳答案
如果它们除了文本和图像外都一样,那么您实际上只需要 1 个 Activity 类即可处理所有 10 种情况。您可以在开关中执行的操作是使用文本资源和可绘制资源的 ID 填充一个 Bundle,并将其传递到 Activity 中。
所以你的开关看起来像:
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");
}
关于android - 让我的代码更简单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8344703/