在实现如上图的ListView时,Activity中之前的源码为:
classList_3 = (ListView) findViewById(R.id.classList_3);
final List<Integer> classInfos_3 = new ArrayList<>();
classInfos_3.add(R.string.point_C1); //多线程开发
classInfos_3.add(R.string.point_C2); //多进程开发
classInfos_3.add(R.string.point_C3);
ClassListAdpter_Integer classListAdpter_Integer_3 = new ClassListAdpter_Integer(MainActivity.this, classInfos_3);
classList_3.setAdapter(classListAdpter_Integer_3);
classList_3.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
startActivity(new Intent(MainActivity.this, Point_B1_Activity.class));
break;
case 1:
startActivity(new Intent(MainActivity.this, Point_B2_Activity.class));
break;
case 2:
startActivity(new Intent(MainActivity.this, Point_B3_Activity.class));
break;
}
}
});
只将相应字符串的ID值传入List,然后在OnItenClickListener中通过swtich(position)来进行点击跳转。可做如下优化:
classList_2 = (ListView) findViewById(R.id.classList_2);
final List<ActivityItem> classInfos_2 = new ArrayList<>();
classInfos_2.add(new ActivityItem(R.string.point_B1, Point_B1_Activity.class));
classInfos_2.add(new ActivityItem(R.string.point_B2, Point_B2_Activity.class)); //管理文件
classInfos_2.add(new ActivityItem(R.string.point_B3, Point_B3_Activity.class)); //SQLite
classInfos_2.add(new ActivityItem(R.string.point_B4, Point_B4_Activity.class)); //ContentProvider
classInfos_2.add(new ActivityItem(R.string.point_B5, Point_B5_Activity.class));
classInfos_2.add(new ActivityItem(R.string.point_B6, Point_B6_Activity.class));
classInfos_2.add(new ActivityItem(R.string.point_B7, Point_B7_Activity.class));
ClassListAdpter_Activity classListAdpter_Activity_2 = new ClassListAdpter_Activity(MainActivity.this, classInfos_2);
classList_2.setAdapter(classListAdpter_Activity_2);
classList_2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(MainActivity.this, classInfos_2.get(position).getItemActivity()));
}
});
其中,ActivityItem类如下:
public class ActivityItem {
private int mItemName;
private Class mItemActivity;
public ActivityItem(int itemName, Class itemActivity) {
mItemName = itemName;
mItemActivity = itemActivity;
}
public int getItemName() {
return mItemName;
}
public void setItemName(int itemName) {
this.mItemName = itemName;
}
public Class getItemActivity() {
return mItemActivity;
}
public void setItemActivity(Class itemActivity) {
this.mItemActivity = itemActivity;
}
}
简单的优化,将要跳转到的Activity作为ActivityItem类的成员之一,OnItenClickListener中的代码大为简化,再无需使用swtich(position)来进行判断。虽然增加了一个类,但项目的代码较为优化,符合相应的设计思想。