我搜索了谷歌,但没有找到与此有关的任何内容。
我正在使用Android Studio创建我的第一个Material App。现在我想在RecyclerView中显示手机上安装的所有应用程序。这可能吗?
答案 0 :(得分:3)
保存包信息的模型:
class PInfo {
private String appname = "";
private String pname = "";
private String versionName = "";
private int versionCode = 0;
private Drawable icon;
public getAppName(){
return appname;
}
}
CustomAdapter用于设置应用程序名称的值,您还可以通过添加其他代码来显示图标等。通过调用getInstalledApps将返回PInfo类对象,您可以使用它来获取包信息。它需要一个参数,如果你想让系统应用程序发送为false,则传递true(来自此site的代码引用)
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.Viewhold> {
ArrayList<PInfo> appn;
public CustomAdapter() {
appn=p.getInstalledApps(true);
}
@Override
public int getItemCount() {
return appn.size();
}
@Override
public void onBindViewHolder(Viewhold holder, int pos) {
for(int i=0;i<appn.size();i++{
holder.appname.setText(appn.get(i).pname);
}
}
@Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.yourlayout, viewGroup, false);
return new ContactViewHolder(itemView);
}
private ArrayList<PInfo> getPackages() {
ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
final int max = apps.size();
for (int i=0; i<max; i++) {
apps.get(i).prettyPrint();
}
return apps;
}
private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {
ArrayList<PInfo> res = new ArrayList<PInfo>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for(int i=0;i<packs.size();i++) {
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue ;
}
PInfo newInfo = new PInfo();
newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(newInfo);
}
return res;
}
public static class ContactViewHolder extends RecyclerView.ViewHolder{
TextView appname;
public ViewHolder(View v) {
super(v);
appname = (TextView) v.findViewById(R.id.appname);
}
}
}
<强> yourlayout.xml 强>
<TextView
android:id="@+id/secondLine"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="@id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:text="Description"
android:textSize="12sp" />
只需在主要活动中调用以下适配器:
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new CustomAdapter();
mRecyclerView.setAdapter(mAdapter);
访问该网站,了解Recyclerview http://www.vogella.com/tutorials/AndroidRecyclerView/article.html