【发布时间】:2018-03-21 17:45:08
【问题描述】:
所以我对 Android Studio 和一般的应用程序开发很陌生,我有一段时间遇到这个问题,没有解决它的运气。我认为这里的某个人可能会提供一些解决此问题的想法.. 问题:在 UI 线程上刷新 ListView(建议 here)对我不起作用。这是“可运行运行”的声明(在 MainActivity.java 中):
public Runnable run;
// ...
run = new Runnable() {
public void run() {
ArrayList<String> temp1 = (ArrayList<String>) arrayList_1.clone();
View v = getLayoutInflater().inflate(R.layout.fragment_main, null);
lv_1 = (ListView) v.findViewById(R.id.listViewMe);
lv_1.setAdapter(adapter_1);
arrayList_1.clear();
arrayList_1.addAll(temp1);
adapter_1.notifyDataSetChanged();
lv_1.invalidateViews();
lv_1.refreshDrawableState();
Log.e("gig", "DONE REFRESHING");
}
};
我在这里调用方法:
@Override
public boolean onNavigationItemSelected(MenuItem item)
{
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.nav_main) {
fragment = new FragmentMain();
} if (id == R.id.nav_history) {
fragment = new FragmentHistory();
}
if (fragment != null)
{
FragmentTransaction localFragmentTransaction = getSupportFragmentManager().beginTransaction();
localFragmentTransaction.replace(R.id.screen_area, fragment);
localFragmentTransaction.commit();
runOnUiThread(run); // here
}
((DrawerLayout) findViewById(R.id.drawer_layout)).closeDrawer(GravityCompat.START);
return true;
}
现在让我感到困惑的部分是:当我通过此方法向 ListView 添加新项目时它会起作用:
public void addDebtToOther(String name, String money)
{
String full = name + ", " + money + " EUR";
lv_1 = (ListView) findViewById(R.id.listViewMe);
if (lv_1!=null) {
lv_1.setAdapter(adapter_1);
arrayList_1.add(full);
adapter_1.notifyDataSetChanged();
} else {
Log.e("gig", "ListView error, lv is NULL");
}
}
就是这样,任何帮助都会非常感激!
【问题讨论】:
-
onNavigationItemSelected()已经调用了你不需要的主线程runOnUiThread。 -
所以我应该尝试用
run()的所有内容替换runOnUiThread(run)? -
是的,你可以直接调用它。只需将整个代码放在一个方法中并调用它。
-
仍然没有运气.. 如果我通过
addDebtToOther()方法将另一个项目添加到列表视图中,则效果很好。
标签: android listview android-studio android-runonuithread