2013-05-28
导语:只是在学习中找的一些东西,小小测试代码,自己记录一下,后续用,勿喷。
正文:
本文代码仅为自己测试,记录下来的代码,百度随处可见的代码。代码中显示一个简单的ListView然后把App的图标和名字显示出来,如此简单。
xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageView
android:id="@+id/test2_image"
android:layout_width="40dip"
android:layout_height="40dip"
android:layout_margin="1dip"
android:contentDescription="show icon"
/>
<TextView
android:id="@+id/test2_text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:textSize="12sp"
/>
</LinearLayout>
ListActivity
public class Test2_AppInfo extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PackageManager pm = this.getPackageManager();
//get the packages, can use other flag for more information
List<PackageInfo> packageInfos = pm.getInstalledPackages(PackageManager.GET_ACTIVITIES);
//init the list
List<HashMap<String, Object>> map = new ArrayList<HashMap<String,Object>>();
for(PackageInfo p : packageInfos) {
HashMap<String, Object> m = new HashMap<String, Object>();
m.put("icon", p.applicationInfo.loadIcon(pm));
m.put("name", p.applicationInfo.loadLabel(pm).toString());
map.add(m);
}
Collections.sort(map, new Test2Comparator());//to sort the hash map by unicode value
ListAdapter adapter = new Test2Adapter(this, map);
setListAdapter(adapter);//set the adapter to this listview
}
/**
* a easy sort comparator
*/
public class Test2Comparator implements Comparator<HashMap<String, Object>> {
public int compare(HashMap<String, Object> lhs,
HashMap<String, Object> rhs) {
String str1 = lhs.get("name").toString();
String str2 = rhs.get("name").toString();
if(str1.toUpperCase().compareTo(str2.toUpperCase()) < 0)
return -1;
else if(str1.toUpperCase().compareTo(str2.toUpperCase()) > 0)
return 1;
else
return 0;
}
}
/**
* a test adapter to display the list data
*/
public class Test2Adapter extends BaseAdapter {
private List<HashMap<String, Object>> mMap;
private LayoutInflater mLayoutInflater;
public Test2Adapter(Context context, List<HashMap<String, Object>>map) {
mMap = map;
mLayoutInflater = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return mMap.size();
}
public Object getItem(int position) {
return mMap.get(position);
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
HashMap<String, Object> map = mMap.get(position);
View view = mLayoutInflater.inflate(R.layout.list_item_test2, null);
ImageView iv = (ImageView)view.findViewById(R.id.test2_image);
TextView tv = (TextView)view.findViewById(R.id.test2_text);
iv.setBackgroundDrawable((Drawable) map.get(("icon")));
tv.setText(map.get("name").toString());
return view;
}
}
}
结尾: 1)坚持写写博客
2)继续学习安卓
3)我是IT程序猿