首先,看一下整个程序的运行结果:
图1.
图2
.图3.
图4.
下面来编写代码实现上述结果:
一、LauncherActivity的使用
LauncherActivity本质上是一个开发列表界面的Acticity,与普通的列表界面不同的是,它开发出来的列表界面的每个列表项对应于一个Intent,因此当用户点击不同的列表项时,应用程序会启动对应的Activity,需要注意的是继承LauncherActivity时通常应该重写intentForPosition(int position)方法,该方法根据不同的Item返回不同的Intent,从而程序自动启动不同的Activity。
OtherActivity继承LauncherActivity不需要界面布局文件。但通过SimpleAdapter来设置每个Item时需要用到布局文件list.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<!-- 定义一个ImageView作为列表项的一部分 -->
<ImageView
android:id="@+id/header"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:paddingLeft="10dp"
/>
<TextView
android:id="@+id/name"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:textSize="16dp"
android:gravity="center_vertical"
android:paddingLeft="10dp"
/>
</LinearLayout>
OtherActivity.java代码:
package com.example.otheractivity;
import java.util.ArrayList;
public class OtherActivity extends LauncherActivity {
//定义两个Activity的名称
int []imageIds=new int[]{
R.drawable.ic_launcher,
R.drawable.ic_launcher
};
String[] ActivityNames={"设置程序参数","查看星际兵种"};
//定义两个Activity对应的实现类
Class<?>[] classes={ExpandableActivityTest.class,PreferenceActivityTest.class};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//创建一个List集合,List集合的元素是Map
List<Map<String, Object>> listItems=new ArrayList<Map<String,Object>>();
for(int i=0;i<ActivityNames.length;i++){
Map<String, Object> listItem=new HashMap<String, Object>();
listItem.put("header", imageIds[i]);
listItem.put("personName", ActivityNames[i]);
listItems.add(listItem);
}
SimpleAdapter simpleAdapter=new SimpleAdapter(this, listItems, R.layout.list, new String[]{"personName","header"}, new int[]{R.id.name,R.id.header});
//设置该窗口现实的列表所需的Adapter
setListAdapter(simpleAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_other, menu);
return true;
}
@Override
protected Intent intentForPosition(int position) {
// TODO Auto-generated method stub
return new Intent(OtherActivity.this, classes[position]);
}
}
运行结果如上图中的图1,上面的程序还用到了两个Activity:ExpandableListActivityTest和PreferenceActivityTest,这两个Activity是分别通过继承ExpandableListActivity和PreferenceActivity来实现的。下一篇文章将介绍这两个Activity中的实现。