【问题标题】:Populate a ListView in fragment correct正确填充片段中的 ListView
【发布时间】:2016-11-15 12:08:40
【问题描述】:

我在片段中有一个 ListView,我想用来自 REST API 的数据填充列表。

REST 请求需要 1-3 秒。 现在我想在后台执行此操作。

我试过了

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    final View view =  inflater.inflate(R.layout.fragment_watchlist, container, false);
    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            //Execute Request in Thread
            // adapter = ....
            recyclerView.setAdapter(adapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        }
     }, 1000);

     return view;

如果我调试这个函数,一切都会被执行。

但列表从未绘制出来。

仅限:如果我单击应用主栏上的搜索栏。然后我可以看到列表。

2 天前一切正常。但是我不知道错在哪里。

这是我的导航功能:

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    Fragment fragment = null;
    String title = getString(R.string.app_name);

    int id = item.getItemId();

    if (id == R.id.nav_news) {
        fragment = new NewsFragment();
    } else if (id == R.id.nav_charts) {
        fragment = new ChartFragment();
    } else if (id == R.id.nav_favorites) {
        fragment = new FavoriteFragment();
    } else if (id == R.id.nav_profile) {
        fragment = new ProfileFragment();
    } else if (id == R.id.nav_settings) {
        throw new NotImplementedException("Fragment not Implemented");
    }

    android.support.v4.app.FragmentTransaction fragmentTransaction =
            getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragment);
    fragmentTransaction.commit();

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);

    return true;
}

【问题讨论】:

  • 我也同意 sasikumar 的观点,将任务分解为更小的方法。类似 1. getData() - 创建这样的方法,使用 AsyncTask、IntentService 或线程在后台获取数据。 2. displayData() - 一旦你得到数据,解析它并将其转换为java对象,只需使用java对象来填充你的列表视图。
  • 但是我需要在我的 onCreateView() 函数中调用 displayData() 函数来获取片段的View 对象。如果我在 displayData() 方法中尝试getView(),则视图为空

标签: android multithreading listview android-fragments


【解决方案1】:

我建议您调用片段的 REST API oncreateview() 并在 Web api 响应方法中设置适配器(检查成功)。如果您想刷新适配器,请在片段中使用 onResume() 方法。

【讨论】:

  • 你能解释一下吗?您的意思是 onCreateView 中的 REST API 调用和 onResume 中的适配器分配?
  • 根据您的 webApi 响应设置适配器
  • 但是如何在 onCreateView 函数之外获取视图?
猜你喜欢
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2019-05-31
  • 2015-06-16
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
相关资源
最近更新 更多