在我的Android应用中,recyclerView
中有一个fragment
。因此recyclerView
承载了有关已安装应用程序的详细信息。我正在使用customAdapter
,并通过线程将数据加载到recyclerView
,因为如果没有,则UI会挂起。我正在使用swipetoReload控件。我可以通过重新启动使用的线程来重新加载recylerView。但是recyclerView
消失了,并立即再次出现。
我在这里做错什么了吗?有办法避免这种情况。还是有更好的方法来执行此操作而无需线程或类似的东西。 这是我的代码。
片段:
Thread loadApps = new Thread() {
@Override
public void run() {
swipeapplist.post(new Runnable() {
@Override
public void run() {
if (!swipeapplist.isRefreshing()) {
swipeapplist.setRefreshing(true);
}
}
});
appAdapter = new AppAdapter(context, getInstalledApps());
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
recyclerInstalledApps.post(new Runnable() {
@Override
public void run() {
recyclerInstalledApps.setLayoutManager(layoutManager);
LayoutAnimationController controller = AnimationUtils.loadLayoutAnimation(context, R.anim.recycler_layout_animation);
recyclerInstalledApps.setLayoutAnimation(controller);
recyclerInstalledApps.scheduleLayoutAnimation();
recyclerInstalledApps.setAdapter(appAdapter);
}
});
swipeapplist.post(new Runnable() {
@Override
public void run() {
if (swipeapplist.isRefreshing()) {
swipeapplist.setRefreshing(false);
}
}
});
}
};
loadApps.start();
获取应用信息的方法
private ArrayList<AppInfo> getInstalledApps() {
ArrayList<AppInfo> res = new ArrayList<>();
try {
if (context != null) {
pm = context.getPackageManager();
List<PackageInfo> packs = pm.getInstalledPackages(PackageManager.GET_PERMISSIONS);
Collections.sort(packs, new Comparator<PackageInfo>() {
@Override
public int compare(PackageInfo arg0, PackageInfo arg1) {
CharSequence name0 = arg0.applicationInfo.loadLabel(pm);
CharSequence name1 = arg1.applicationInfo.loadLabel(pm);
return name0.toString().compareTo(name1.toString());
}
});
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
if ((!isSystemPackage(p))) {
String appName = p.applicationInfo.loadLabel(context.getPackageManager()).toString();
String packageName = p.applicationInfo.packageName;
String appVersion = "Version : " + p.versionName;
Drawable icon = p.applicationInfo.loadIcon(context.getPackageManager());
res.add(new AppInfo(appName, packageName, appVersion, icon));
}
}
}
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return res;
}
答案 0 :(得分:1)
尝试使用notifyDataSetChanged
appAdapter = new AppAdapter(context, getInstalledApps());
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
recyclerInstalledApps.post(new Runnable() {
@Override
public void run() {
recyclerInstalledApps.setLayoutManager(layoutManager);
LayoutAnimationController controller = AnimationUtils.loadLayoutAnimation(context, R.anim.recycler_layout_animation);
recyclerInstalledApps.setLayoutAnimation(controller);
recyclerInstalledApps.scheduleLayoutAnimation();
recyclerInstalledApps.setAdapter(appAdapter);
}
});
appAdapter.notifyDataSetChanged();